coco_pipe.viz.dim_reduction#
Matplotlib visualization helpers for dimensionality reduction outputs.
Functions#
|
Plot an explicit 2D or 3D embedding. |
|
Plot tidy metric observations using one shared entrypoint. |
|
Plot reducer loss history. Linear reducers usually do not expose this. |
|
Plot explained variance curves from linear reducers (PCA, TruncatedSVD). |
|
Plot original vs embedded pairwise distances. |
|
Plot a velocity field on a 2D embedding. |
|
Plot feature-importance scores as horizontal bars. |
|
Plot feature-to-dimension correlations as a heatmap. |
|
Plot evaluated trajectory metric time series. |
|
Plot prepared trajectory tensors of shape |
|
Heatmap of a co-ranking matrix produced by |
|
Pairwise label-separation timecourses for trajectory embeddings. |
|
Heatmap of component loadings from linear reducers. |
|
Plot a phase portrait (amplitude vs velocity) for condition-mean trajectories. |
|
Creates a scree plot. |
Module Contents#
- coco_pipe.viz.dim_reduction.plot_embedding(X_emb, labels=None, metadata=None, dims=(0, 1), title='Embedding', figsize=(10, 8), cmap=None, palette='deep', s=40, alpha=0.8, label_kind='categorical', metrics=None, metric_name=None, ax=None, random_state=None)#
Plot an explicit 2D or 3D embedding.
- Parameters:
X_emb (numpy.ndarray) – Embedding array with shape
(n_samples, n_dimensions).labels (numpy.ndarray | None) – Optional label array aligned with samples used for color encoding.
metadata (dict[str, Any] | None) – Optional column-oriented metadata aligned with samples.
dims (tuple[int, int] | tuple[int, int, int]) – Column indices to use as plot axes. Two indices produce a 2D plot; three produce a 3D plot.
title (str) – Axes title.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
cmap (str | None) – Colormap used when
label_kind="continuous".palette (str) – Seaborn palette name used when
label_kind="categorical".s (int) – Scatter marker size.
alpha (float) – Scatter point opacity.
label_kind (coco_pipe.viz.theme.ColorKind) –
"categorical"to color by class,"continuous"to apply a colormap to numeric labels.metrics (dict[str, Any] | None) – Optional metrics mapping used to annotate the plot when
metric_nameis provided.metric_name (str | None) – Name of the metric from
metricsto display as an annotation.ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
random_state (int | None) – Accepted for API compatibility; not used internally.
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_embeddingInteractive Plotly version.
plot_metricsQuality metric overview for the embedding run.
plot_shepard_diagramDistance-preservation diagnostic.
plot_eigenvaluesExplained variance for linear reducers.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> X_emb = rng.normal(size=(50, 2)) >>> labels = np.arange(50) % 5 >>> fig, ax = viz.plot_embedding(X_emb, labels=labels)
- coco_pipe.viz.dim_reduction.plot_metrics(scores, title='Quality Metrics', figsize=(8, 6), ax=None, plot_type='bar', metric=None, scope=None, method=None, axes_kws=None)#
Plot tidy metric observations using one shared entrypoint.
- Parameters:
scores (Any) – Metric source: a tidy DataFrame,
{metric: value}mapping, list of records, or any object exposingto_frame()ormetrics_.title (str) – Axes title.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
plot_type (Literal['bar', 'grouped_bar', 'lollipop', 'box', 'boxen', 'violin', 'raincloud', 'strip', 'swarm', 'heatmap', 'line', 'dumbbell', 'slopegraph']) – Visualization style.
"bar"/"grouped_bar"/"lollipop"aggregate to global scalars;"box"/"boxen"/"violin"/"raincloud"/"strip"/"swarm"show per-observation distributions;"heatmap"produces a method x metric grid;"line"plots metrics across a numeric scope axis;"dumbbell"/"slopegraph"require exactly two methods.metric (str | None) – Optional metric name used to filter rows before plotting.
scope (str | None) – Optional scope name used to filter rows before plotting.
method (str | collections.abc.Sequence[str] | None) – Optional method name or names used to filter rows before plotting.
axes_kws (dict | None)
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_metricsInteractive Plotly version.
plot_embedding2D or 3D scatter of the embedding points.
plot_eigenvaluesPer-component explained variance.
plot_coranking_matrixNeighbourhood-preservation co-ranking heatmap.
Examples
>>> from coco_pipe.viz import dim_reduction as viz >>> fig, ax = viz.plot_metrics({"trustworthiness": 0.92, "continuity": 0.88})
- coco_pipe.viz.dim_reduction.plot_loss_history(loss_history, title='Training Loss', figsize=(8, 5), ax=None, scope=None, axes_kws=None)#
Plot reducer loss history. Linear reducers usually do not expose this.
- Parameters:
loss_history (collections.abc.Sequence[float] | numpy.ndarray) – Sequence of per-epoch loss values from an iterative reducer.
title (str) – Axes title.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
scope (str | None) – Optional scope tag, accepted as
"train"or"val".axes_kws (dict | None)
- Returns:
The created or reused figure and axes.
- Return type:
- Raises:
ValueError – If
loss_historyis empty orscopeis not"train"or"val".
See also
coco_pipe.viz.interactive.dim_reduction.plot_loss_historyInteractive Plotly version.
plot_eigenvaluesExplained variance for linear reducers.
plot_metricsScalar quality metric overview.
Examples
>>> from coco_pipe.viz import dim_reduction as viz >>> fig, ax = viz.plot_loss_history([1.0, 0.7, 0.4, 0.25, 0.18])
- coco_pipe.viz.dim_reduction.plot_eigenvalues(values, title='Scree Plot', ylabel='Explained Variance', figsize=(8, 5), ax=None, max_components=None, condition_colors=None, axes_kws=None)#
Plot explained variance curves from linear reducers (PCA, TruncatedSVD).
- Parameters:
values (dict[str, np.ndarray]) –
Mapping of label → array. Array shapes:
1-D
(n_pcs,)— pre-averaged curve, no SEM band.2-D
(n_subjects, n_pcs)— per-subject data; mean ± SEM band drawn.
max_components (int, optional) – Cap the number of components shown.
condition_colors (dict[str, str], optional) – Per-label hex colour overrides.
title (str)
ylabel (str)
ax (matplotlib.pyplot.Axes | None)
axes_kws (dict | None)
- Return type:
tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes]
See also
coco_pipe.viz.interactive.dim_reduction.plot_eigenvaluesInteractive Plotly version.
plot_metricsScalar quality metric overview.
plot_loss_historyIterative training loss curve.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> evals = {"PCA": np.array([0.50, 0.30, 0.12, 0.05, 0.03])} >>> fig, ax = viz.plot_eigenvalues(evals)
- coco_pipe.viz.dim_reduction.plot_shepard_diagram(X_orig, X_emb, sample_size=1000, title='Shepard Diagram', ax=None, random_state=None, distances=None, figsize=None)#
Plot original vs embedded pairwise distances.
- Parameters:
X_orig (numpy.ndarray) – Original high-dimensional data with shape
(n_samples, n_features). Ignored whendistancesis provided.X_emb (numpy.ndarray) – Low-dimensional embedding with shape
(n_samples, n_dims). Ignored whendistancesis provided.sample_size (int) – Number of point pairs to sample for distance computation.
title (str) – Axes title.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
random_state (int | None) – Random seed for reproducible distance sampling.
distances (dict[str, numpy.ndarray] | None) – Pre-computed distance dict with
"original"and"embedded"keys. When both keys are present,X_origandX_embare not used.figsize (tuple[float, float] | None) – Figure size used when creating new axes.
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_shepard_diagramInteractive Plotly version.
plot_embeddingScatter of the low-dimensional embedding.
plot_coranking_matrixNeighbourhood-rank preservation heatmap.
plot_metricsScalar quality metrics such as trustworthiness.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> X_orig = rng.normal(size=(60, 10)) >>> X_emb = rng.normal(size=(60, 2)) >>> fig, ax = viz.plot_shepard_diagram(X_orig, X_emb, sample_size=200)
- coco_pipe.viz.dim_reduction.plot_streamlines(X_emb, V_emb, grid_density=25, title='Velocity Streamlines', ax=None, random_state=None, figsize=None)#
Plot a velocity field on a 2D embedding.
- Parameters:
X_emb (numpy.ndarray) – 2D embedding coordinates with shape
(n_samples, 2).V_emb (numpy.ndarray) – Velocity vectors with the same shape as
X_emb, as returned bycoco_pipe.dim_reduction.evaluation.velocity.compute_velocity_fields.grid_density (int) – Number of grid points per axis used for velocity interpolation.
title (str) – Axes title.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
random_state (int | None) – Accepted for API compatibility; not used internally.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_streamlinesInteractive Plotly version.
plot_embeddingScatter of the underlying embedding points.
plot_trajectoryPlotted trajectory paths over the embedding.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> X_emb = rng.normal(size=(80, 2)) >>> V_emb = rng.normal(size=(80, 2)) * 0.2 >>> fig, ax = viz.plot_streamlines(X_emb, V_emb)
- coco_pipe.viz.dim_reduction.plot_feature_importance(scores, title='Feature Importance', top_n=20, figsize=(8, 6), ax=None, analysis=None, method=None, dimension=None)#
Plot feature-importance scores as horizontal bars.
- Parameters:
scores (Any) – Feature-score source: a raw
{feature: score}mapping, interpretation payload, tidy interpretation DataFrame, or any object exposinginterpretation_.title (str) – Axes title.
top_n (int) – Maximum number of features to display, ranked by score magnitude.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
analysis (str | None) – Interpretation analysis to select when multiple analyses are present.
method (str | None) – Method name to select when multiple methods are present.
dimension (str | None) – Dimension label to select when multiple dimensions are present.
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_feature_importanceInteractive Plotly version.
plot_feature_correlation_heatmapFeature-to-dimension correlation heatmap.
plot_component_loadingsLinear-reducer component loading matrix.
Examples
>>> from coco_pipe.viz import dim_reduction as viz >>> scores = {"alpha": 0.72, "beta": 0.55, "gamma": 0.31} >>> fig, ax = viz.plot_feature_importance(scores)
- coco_pipe.viz.dim_reduction.plot_feature_correlation_heatmap(correlations, title='Feature Correlation', top_n=25, figsize=(10, 8), ax=None, method=None)#
Plot feature-to-dimension correlations as a heatmap.
- Parameters:
correlations (Any) – Correlation source: a raw correlation payload, tidy interpretation DataFrame, or any object exposing
interpretation_.title (str) – Axes title.
top_n (int | None) – Maximum number of features to show, ranked by peak absolute correlation across dimensions.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
method (str | None) – Method name to select when multiple methods are present.
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_feature_correlation_heatmapInteractive Plotly version.
plot_feature_importanceRanked feature-importance bar chart.
plot_component_loadingsLinear-reducer component loading matrix.
Examples
>>> from coco_pipe.viz import dim_reduction as viz >>> payload = { ... "correlation": {"D1": {"F1": 0.6, "F2": -0.3}, "D2": {"F1": 0.1, "F2": 0.8}} ... } >>> fig, ax = viz.plot_feature_correlation_heatmap(payload)
- coco_pipe.viz.dim_reduction.plot_trajectory_metric_series(series, times=None, labels=None, color_map=None, linestyle_map=None, smooth_window=1, title='Trajectory Metric', ylabel='Value', figsize=(10, 6), ax=None)#
Plot evaluated trajectory metric time series.
- Parameters:
series (Any) – Metric values: a 1D array, 2D
(trajectory, time)array, or a{name: timecourse}mapping. 2D arrays are averaged across trajectories per unique label.times (numpy.ndarray | None) – Explicit time axis aligned with the time dimension.
labels (numpy.ndarray | None) – Trajectory labels aligned with the first axis of 2D inputs.
title (str) – Axes title.
ylabel (str) – Y-axis label.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
smooth_window (int)
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_trajectory_metric_seriesInteractive Plotly version.
plot_trajectoryRaw trajectory paths in embedding space.
plot_trajectory_separationPairwise label-separation timecourses.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> series = rng.normal(size=(3, 20)) >>> fig, ax = viz.plot_trajectory_metric_series(series)
- coco_pipe.viz.dim_reduction.plot_trajectory(X, times=None, values=None, labels=None, color_map=None, linestyle_map=None, smooth_window=1, downsample=1, speed_mode='linecollection', add_start_end_markers=False, show_markers=True, xlim=None, ylim=None, linewidth=2.5, title='Trajectory Plot', dimensions=2, figsize=(10, 8), ax=None, cmap=None, axis_labels=None, axes_kws=None, showlegend=True)#
Plot prepared trajectory tensors of shape
trajectory x time x dim.- Parameters:
X (np.ndarray of shape (n_trajectories, n_times, n_dims)) – Each trajectory along the first axis — can be individual subjects, pre-averaged conditions, or any other grouping.
times (np.ndarray, optional) – Time stamps for the time axis. Defaults to integer indices.
values (np.ndarray of shape (n_trajectories, n_times), optional) – Per-point scalar values (e.g. speed) used for colour encoding.
labels (array-like of length n_trajectories, optional) – Label per trajectory used for colouring and legend.
color_map (dict[str, str], optional) – Optional mapping of label to hex color string.
linestyle_map (dict[str, str], optional) – Optional mapping of label to Matplotlib linestyle string.
smooth_window (int, default=1) – Moving-average window applied before plotting.
downsample (int, default=1) – Keep every
downsample-th time point.speed_mode ({"linecollection", "alpha"}, default="linecollection") – Colour-encoding style when
valuesis provided (2D only)."linecollection"colours each segment by value;"alpha"modulates transparency and lightness of the base colour.add_start_end_markers (bool, default=False) – Draw a circle (●) at the start and a cross (✕) at the end of each trajectory instead of a marker on every point.
show_markers (bool, default=True) – If True, draws markers at each sampled time point unless
add_start_end_markersis True.xlim (tuple[float, float], optional) – Fixed axis limits. Auto-scaled when
None.ylim (tuple[float, float], optional) – Fixed axis limits. Auto-scaled when
None.linewidth (float, default=2.5)
title (str, default="Trajectory Plot")
dimensions (int, default=2) – Number of spatial dimensions to render (2 or 3).
ax (matplotlib.axes.Axes, optional)
cmap (str, optional) – Colormap name for value encoding. Defaults to the theme sequential map.
axis_labels (list[str], optional) – Custom axis labels (e.g.
["PC1", "PC2"]).axes_kws (dict, optional) – Additional kwargs passed to
ax.set().showlegend (bool, default=True) – Whether to draw the legend.
- Return type:
tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes]
See also
coco_pipe.viz.interactive.dim_reduction.plot_trajectoryInteractive Plotly version.
plot_trajectory_separationPairwise label-separation timecourses.
plot_trajectory_metric_seriesMetric time series for trajectories.
plot_streamlinesVelocity field overlay on the embedding.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> X = rng.normal(size=(3, 20, 2)) >>> labels = np.array(["A", "B", "C"]) >>> fig, ax = viz.plot_trajectory(X, labels=labels)
- coco_pipe.viz.dim_reduction.plot_coranking_matrix(coranking_matrix, title='Co-Ranking Matrix', max_k=None, ax=None, figsize=None)#
Heatmap of a co-ranking matrix produced by
DimReduction.score().- Parameters:
coranking_matrix (numpy.ndarray) – Square co-ranking matrix with shape
(n_samples-1, n_samples-1).title (str) – Axes title.
max_k (int | None) – Crop the matrix to the top-left
max_k x max_kcorner. Defaults tomin(n, 50).ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_coranking_matrixInteractive Plotly version.
plot_shepard_diagramContinuous distance-preservation scatter.
plot_metricsScalar quality metric overview.
plot_embeddingLow-dimensional scatter being diagnosed.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> Q = np.random.default_rng(42).integers(0, 10, size=(15, 15)).astype(float) >>> fig, ax = viz.plot_coranking_matrix(Q)
- coco_pipe.viz.dim_reduction.plot_trajectory_separation(separation, times=None, top_n=None, color_map=None, linestyle_map=None, smooth_window=1, ax=None, figsize=None)#
Pairwise label-separation timecourses for trajectory embeddings.
- Parameters:
separation (dict) – Mapping of
(label_a, label_b)tuples (or any hashable key) to 1D separation timecourses, as returned byDimReduction.evaluate_trajectory.times (numpy.ndarray | None) – Explicit time axis aligned with the separation arrays.
top_n (int | None) – Keep only the
top_npairs ranked by peak separation.color_map (dict[tuple, str] | None) – Optional mapping of pair key to color.
linestyle_map (dict[tuple, str] | None) – Optional mapping of pair key to linestyle.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
smooth_window (int)
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_trajectory_separationInteractive Plotly version.
plot_trajectoryRaw trajectory paths in embedding space.
plot_trajectory_metric_seriesMetric time series for trajectories.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> sep = { ... ("A", "B"): np.linspace(0.1, 0.9, 20), ... ("A", "C"): np.linspace(0.3, 0.6, 20), ... } >>> fig, ax = viz.plot_trajectory_separation(sep)
- coco_pipe.viz.dim_reduction.plot_component_loadings(components, feature_names=None, n_components=None, center=0.0, ax=None, figsize=None)#
Heatmap of component loadings from linear reducers.
- Parameters:
components (numpy.ndarray) – Loading matrix with shape
(n_features, n_components).feature_names (list[str] | None) – Optional feature names for row labels. Defaults to
["Feature 0", "Feature 1", ...].n_components (int | None) – Crop to this many components (columns).
center (float) – Colormap center value for the diverging palette.
ax (matplotlib.pyplot.Axes | None) – Existing Matplotlib axes to draw into.
figsize (tuple[float, float] | None) – Figure size used when creating new axes.
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_component_loadingsInteractive Plotly version.
plot_feature_importanceRanked feature-importance bar chart.
plot_feature_correlation_heatmapFeature-to-dimension correlation heatmap.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> components = rng.normal(size=(12, 3)) >>> fig, ax = viz.plot_component_loadings(components)
- coco_pipe.viz.dim_reduction.plot_phase_portrait(X, times, labels, component_idx=0, title='Phase Portrait', figsize=(8, 10), ax=None, axes_kws=None)#
Plot a phase portrait (amplitude vs velocity) for condition-mean trajectories.
- Parameters:
X (np.ndarray) – Trajectory array with shape
(n_conditions, n_times, n_components).times (np.ndarray) – One-dimensional time axis aligned with the time dimension of
X.labels (sequence) – Condition labels, one per trajectory (first axis of
X).component_idx (int, default=0) – Index of the component to extract for the portrait.
title (str, default="Phase Portrait") – Axes title.
figsize (tuple[float, float], optional) – Figure size used when creating new axes.
ax (matplotlib.axes.Axes, optional) – Existing Matplotlib axes to draw into.
axes_kws (dict | None)
- Returns:
The created or reused figure and axes.
- Return type:
See also
coco_pipe.viz.interactive.dim_reduction.plot_phase_portraitInteractive Plotly version.
plot_trajectoryFull trajectory geometry in 2D or 3D space.
plot_trajectory_metric_seriesScalar metric timecourses per trajectory.
Examples
>>> import numpy as np >>> from coco_pipe.viz import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> X = rng.normal(size=(3, 20, 5)) >>> times = np.linspace(0, 1, 20) >>> fig, ax = viz.plot_phase_portrait(X, times, labels=["A", "B", "C"])
- coco_pipe.viz.dim_reduction.plot_scree(evr, title='Scree Plot', figsize=(8, 10), ax=None, axes_kws=None)#
Creates a scree plot. Plots individual explained variance as bars and cumulative variance as a line.