peach.pl.archetypal#

Archetypal visualization functions.

This module provides publication-ready interactive visualization tools for archetypal analysis results. All plots are built with Plotly for interactivity and can be exported to various formats for publication.

Main Functions: - archetypal_space(): Interactive 3D visualization of archetypal coordinate space - archetypal_space_multi(): Compare multiple archetypal fits side-by-side - training_metrics(): Training diagnostics and convergence analysis - elbow_curve(): Hyperparameter selection support with cross-validation

Features: - Interactive Plotly-based plots with zoom, pan, and hover - Gene expression coloring with smart layer selection - Publication-ready aesthetics and customization options - Automatic legend and colorbar positioning

Functions

archetypal_space(adata, *[, ...])

Visualize cells in 3D archetypal coordinate space.

archetypal_space_multi(adata_list, *[, ...])

Compare multiple archetypal analysis fits in 3D PCA space.

archetype_positions(adata, *[, coords_key, ...])

Visualize archetype positions in PCA space with distance matrix.

archetype_positions_3d(adata, *[, ...])

Visualize archetype positions in 3D PCA space.

archetype_statistics(adata, *[, coords_key, ...])

Compute and display statistics about archetype positions.

elbow_curve(cv_summary, *[, metrics])

Plot elbow curves for hyperparameter selection.

training_metrics(history, *[, height, ...])

Visualize training metrics over epochs.

peach.pl.archetypal.archetypal_space(adata, *, archetype_coords_key='archetype_coordinates', pca_key='X_pca', color_by=None, use_layer='logcounts', cell_size=2.0, cell_opacity=0.6, archetype_size=8.0, archetype_color='red', show_archetype_labels=True, show_connections=True, color_scale='viridis', categorical_colors=None, title='Archetypal Space Visualization', auto_scale=True, save_path=None, fixed_ranges=None, legend_marker_scale=1.0, legend_font_size=12, show_centroids=False, centroid_condition=None, centroid_order=None, centroid_groupby=None, centroid_size=20.0, centroid_start_symbol='circle', centroid_end_symbol='diamond', centroid_line_width=6.0, centroid_colors=None, **kwargs)[source]#

Visualize cells in 3D archetypal coordinate space.

Creates an interactive 3D scatter plot showing cells positioned in PCA space with archetype positions and optional coloring by gene expression or metadata.

Parameters:
  • adata (AnnData) – Annotated data object with archetypal coordinates.

  • archetype_coords_key (str, default: "archetype_coordinates") – Key in adata.uns containing archetype coordinates [n_archetypes, n_pcs].

  • pca_key (str, default: "X_pca") – Key in adata.obsm containing PCA coordinates [n_cells, n_pcs].

  • color_by (str | None, default: None) – Column in adata.obs (categorical/continuous) or gene name in adata.var.index for expression coloring.

  • use_layer (str, default: "logcounts") – Layer for gene expression. Falls back to adata.X if not found.

  • cell_size (float, default: 2.0) – Size of cell points.

  • cell_opacity (float, default: 0.6) – Opacity of cell points (0-1).

  • archetype_size (float, default: 8.0) – Size of archetype diamond markers.

  • archetype_color (str, default: "red") – Color for archetype markers.

  • show_archetype_labels (bool, default: True) – Whether to show ‘Arch1’, ‘Arch2’, etc. labels.

  • show_connections (bool, default: True) – Whether to draw lines connecting all archetype pairs.

  • color_scale (str, default: "viridis") – Plotly color scale for continuous variables.

  • categorical_colors (dict | None, default: None) – Custom colors for categorical variables {category: color}.

  • title (str, default: "Archetypal Space Visualization") – Plot title.

  • auto_scale (bool, default: True) – Whether to auto-scale axes using 1st-99th percentiles.

  • save_path (str | None, default: None) – Path to save HTML file.

  • fixed_ranges (dict | None, default: None) – Fixed axis ranges {‘x’: (min, max), ‘y’: (min, max), ‘z’: (min, max)}.

  • legend_marker_scale (float, default: 1.0) – Scale factor for legend marker sizes.

  • legend_font_size (int, default: 12) – Font size for legend text.

  • show_centroids (bool, default: False) – Whether to display condition centroids on the plot. Requires centroids computed via pc.tl.compute_conditional_centroids().

  • centroid_condition (str | None, default: None) – Column name in adata.obs for condition centroids. Must have centroids pre-computed via pc.tl.compute_conditional_centroids().

  • centroid_order (list | None, default: None) – Order of condition levels for trajectory line. If provided, draws a line connecting centroids in this order. Example: [‘chemo-naive’, ‘IDS’] for treatment timeline.

  • centroid_groupby (str | None, default: None) – Column name for multi-group trajectories. If provided, draws separate trajectory per group with different colors.

  • centroid_size (float, default: 20.0) – Size of centroid markers.

  • centroid_start_symbol (str, default: "circle") – Plotly symbol for first centroid in trajectory.

  • centroid_end_symbol (str, default: "diamond") – Plotly symbol for last centroid in trajectory.

  • centroid_line_width (float, default: 6.0) – Width of trajectory line connecting centroids.

  • centroid_colors (dict | None, default: None) – Custom colors for centroid markers/lines. If centroid_groupby used: {group: color} (e.g., {‘long’: ‘magenta’, ‘short’: ‘cyan’}). Otherwise: {‘default’: color}.

  • **kwargs – Additional arguments passed to underlying visualization.

Returns:

Interactive 3D scatter plot containing: - Cell points colored by color_by (with colorbar if continuous) - Archetype positions as diamond markers - Archetype labels (if show_archetype_labels=True) - Hull edges connecting archetypes (if show_connections=True) - Condition centroids with trajectory lines (if show_centroids=True)

Return type:

plotly.graph_objects.Figure

Raises:

ValueError – If adata.obsm[‘archetype_distances’] not found (run pc.tl.archetypal_coordinates() first).

Examples

>>> # Color by cell type metadata
>>> fig = pc.pl.archetypal_space(adata, color_by="cell_type")
>>> fig.show()
>>> # Color by gene expression
>>> fig = pc.pl.archetypal_space(adata, color_by="CD3D")
>>> fig.show()
>>> # Custom styling
>>> fig = pc.pl.archetypal_space(
...     adata, color_by="pseudotime", color_scale="plasma", cell_opacity=0.4, archetype_size=12.0
... )
>>> # With condition trajectory centroids
>>> pc.tl.compute_conditional_centroids(adata, "treatment_phase")
>>> fig = pc.pl.archetypal_space(
...     adata,
...     show_centroids=True,
...     centroid_condition="treatment_phase",
...     centroid_order=["chemo-naive", "IDS"],
...     centroid_colors={"default": "magenta"},
... )
>>> # Multi-group trajectories (treatment × response)
>>> pc.tl.compute_conditional_centroids(adata, "treatment_phase", groupby="response")
>>> fig = pc.pl.archetypal_space(
...     adata,
...     show_centroids=True,
...     centroid_condition="treatment_phase",
...     centroid_groupby="response",
...     centroid_order=["chemo-naive", "IDS"],
...     centroid_colors={"long": "magenta", "short": "cyan"},
... )
peach.pl.archetypal.archetypal_space_multi(adata_list, *, archetype_coords_key='archetype_coordinates', pca_key='X_pca', labels_list=None, color_by=None, color_values=None, cell_size=2.0, cell_opacity=0.6, archetype_size=8.0, archetype_colors=None, show_labels=True, auto_scale=True, range_reference=None, fixed_ranges=None, color_scale='viridis', categorical_colors=None, title='Multi-Archetypal Space Comparison', save_path=None)[source]#

Compare multiple archetypal analysis fits in 3D PCA space.

Creates an interactive 3D scatter plot comparing multiple archetypal fits, useful for comparing different conditions, treatments, or parameter settings.

Parameters:
  • adata_list (list of AnnData) – List of AnnData objects with PCA coordinates and archetype results

  • archetype_coords_key (str, default: "archetype_coordinates") – Key in adata.uns containing archetype coordinates

  • pca_key (str, default: "X_pca") – Key in adata.obsm containing PCA coordinates

  • labels_list (list of str | None, default: None) – Labels for each dataset (defaults to ‘Set 1’, ‘Set 2’, etc.)

  • color_by (str | list of str | None, default: None) – Column(s) to color cells by - single string or list per dataset

  • color_values (array | list of arrays | None, default: None) – Direct color values - single array or list per dataset

  • cell_size (float, default: 2.0) – Size of cell points

  • cell_opacity (float, default: 0.6) – Opacity of cell points (0-1)

  • archetype_size (float, default: 8.0) – Size of archetype markers

  • archetype_colors (list of str | None, default: None) – Colors for archetype markers per dataset

  • show_labels (bool | list of int, default: True) – Which datasets to show archetype labels for (bool, list of indices)

  • auto_scale (bool, default: True) – Whether to auto-scale axes based on all data

  • range_reference (int | AnnData | None, default: None) – Reference dataset index or AnnData for axis scaling

  • fixed_ranges (dict | None, default: None) – Fixed axis ranges {‘x’: (min, max), ‘y’: (min, max), ‘z’: (min, max)}

  • color_scale (str, default: 'viridis') – Plotly color scale for continuous variables

  • categorical_colors (dict | None, default: None) – Custom colors for categorical variables

  • title (str, default: 'Multi-Archetypal Space Comparison') – Plot title

  • save_path (str | Path | None, default: None) – Optional path to save HTML file

Returns:

Interactive 3D comparison plot

Return type:

plotly.graph_objects.Figure

Examples

>>> # Compare treatment conditions
>>> fig = pc.pl.archetypal_space_multi(
...     adata_list=[adata_control, adata_treated],
...     labels_list=["Control", "Treated"],
...     color_by=["cell_type", "cell_type"],
...     title="Treatment Effect on Archetypal Space",
... )
>>> fig.show()
>>> # Compare different archetype numbers
>>> fig = pc.pl.archetypal_space_multi(
...     adata_list=[adata_k3, adata_k5, adata_k7],
...     labels_list=["K=3", "K=5", "K=7"],
...     show_labels=[2],  # Only show labels for K=7
...     title="Archetype Number Comparison",
... )
>>> fig.show()
peach.pl.archetypal.training_metrics(history, *, height=400, width=800, display=True, **kwargs)[source]#

Visualize training metrics over epochs.

Creates interactive Plotly visualization with loss components, stability metrics, and convergence analysis.

Parameters:
  • history (dict) – Training history dictionary from pc.tl.train_archetypal(). Expected keys: ‘loss’, ‘archetypal_loss’, ‘KLD’, ‘rmse’, ‘vertex_stability_latent’, ‘vertex_stability_pca’, ‘loss_delta’.

  • height (int, default: 400) – Base plot height in pixels (actual height is 2x for 3 rows).

  • width (int, default: 800) – Plot width in pixels.

  • display (bool, default: True) – Whether to display the plot immediately via fig.show().

  • **kwargs – Additional arguments passed to plot_training_metrics.

Returns:

Interactive training metrics plot with 3-row layout: - Row 1 (40%): Loss metrics (loss, archetypal_loss, KLD, rmse) - Row 2 (30%): Stability metrics (vertex_stability_latent/pca) - Row 3 (30%): Convergence (loss_delta with rolling mean)

Returns None only if history is empty.

Return type:

plotly.graph_objects.Figure or None

Examples

>>> results = pc.tl.train_archetypal(adata, n_archetypes=5)
>>> fig = pc.pl.training_metrics(results["history"], display=False)
>>> fig.write_html("training.html")
peach.pl.archetypal.elbow_curve(cv_summary, *, metrics=['archetype_r2', 'rmse'], **kwargs)[source]#

Plot elbow curves for hyperparameter selection.

Parameters:
  • cv_summary (CVSummary) – Cross-validation results from pc.tl.hyperparameter_search()

  • metrics (list[str], default: ["archetype_r2", "rmse"]) – Metrics to plot

  • **kwargs – Additional arguments passed to plot_elbow_curve

Returns:

Interactive elbow curve plot

Return type:

plotly.graph_objects.Figure

peach.pl.archetypal.archetype_positions(adata, *, coords_key='archetype_coordinates', title='Archetype Positions in PCA Space', figsize=(15, 6), cmap='tab10', show_distances=True, save_path=None, **kwargs)[source]#

Visualize archetype positions in PCA space with distance matrix.

Creates a two-panel visualization showing archetype positions in the first two principal components and a pairwise distance matrix heatmap.

Parameters:
  • adata (AnnData) – Annotated data object with archetype coordinates

  • coords_key (str, default: "archetype_coordinates") – Key in adata.uns containing archetype coordinates

  • title (str, default: "Archetype Positions in PCA Space") – Main figure title

  • figsize (tuple, default: (15, 6)) – Figure size as (width, height)

  • cmap (str, default: 'tab10') – Colormap for archetype points

  • show_distances (bool, default: True) – Whether to show distance matrix panel

  • save_path (str | None, default: None) – Path to save the figure

  • **kwargs – Additional arguments passed to plot_archetype_positions

Returns:

Figure with archetype position visualizations

Return type:

matplotlib.figure.Figure

Examples

>>> fig = pc.pl.archetype_positions(adata)
>>> plt.show()
>>> # Save high-resolution figure
>>> fig = pc.pl.archetype_positions(adata, title="Helsinki EOC Archetype Positions", save_path="archetypes.png")

Notes

The visualization includes: - Left panel: Archetype positions in PC1-PC2 space with convex hull - Right panel: Pairwise distance matrix with values

Requires at least 2 dimensions in archetype coordinates. For 3D visualization, use archetype_positions_3d().

peach.pl.archetypal.archetype_positions_3d(adata, *, coords_key='archetype_coordinates', title='Archetype Positions in 3D PCA Space', figsize=(12, 10), cmap='tab10', save_path=None, **kwargs)[source]#

Visualize archetype positions in 3D PCA space.

Creates an interactive 3D visualization of archetype positions with convex hull edges connecting the archetypes.

Parameters:
  • adata (AnnData) – Annotated data object with archetype coordinates

  • coords_key (str, default: "archetype_coordinates") – Key in adata.uns containing archetype coordinates

  • title (str, default: "Archetype Positions in 3D PCA Space") – Figure title

  • figsize (tuple, default: (12, 10)) – Figure size as (width, height)

  • cmap (str, default: 'tab10') – Colormap for archetype points

  • save_path (str | None, default: None) – Path to save the figure

  • **kwargs – Additional arguments passed to plot_archetype_distances_3d

Returns:

3D visualization of archetypes

Return type:

matplotlib.figure.Figure

Examples

>>> # Basic 3D visualization
>>> fig = pc.pl.archetype_positions_3d(adata)
>>> plt.show()
>>> # Custom visualization
>>> fig = pc.pl.archetype_positions_3d(adata, cmap="Set1", title="3D Archetype Hull")

Notes

Requires at least 3 dimensions in archetype coordinates. The visualization includes convex hull edges connecting archetypes.

peach.pl.archetypal.archetype_statistics(adata, *, coords_key='archetype_coordinates', verbose=True)[source]#

Compute and display statistics about archetype positions.

Calculates pairwise distances, identifies nearest/farthest archetype pairs, and computes convex hull metrics when possible.

Parameters:
  • adata (AnnData) – Annotated data object with archetype coordinates.

  • coords_key (str, default: "archetype_coordinates") – Key in adata.uns containing archetype coordinates.

  • verbose (bool, default: True) – Whether to print statistics to console.

Returns:

Statistics dictionary with keys: - n_archetypes : int - Number of archetypes - n_dimensions : int - Embedding dimensions - mean_distance : float - Mean pairwise Euclidean distance - std_distance : float - Std of pairwise distances - min_distance : float - Minimum pairwise distance - max_distance : float - Maximum pairwise distance - distance_range : float - max - min distance - nearest_pair : tuple[int, int] - Indices of nearest pair (0-based) - farthest_pair : tuple[int, int] - Indices of farthest pair (0-based) - distance_matrix : np.ndarray - Full pairwise distance matrix - hull_volume : float | None - Convex hull volume (3D+ only) - hull_area : float | None - Convex hull surface area (3D+ only)

Return type:

dict

Raises:

ValueError – If adata.uns[coords_key] not found.

Examples

>>> stats = pc.pl.archetype_statistics(adata)
[STATS] Archetype Statistics
==================================================
Number of archetypes: 5
...
>>> # Quiet mode
>>> stats = pc.pl.archetype_statistics(adata, verbose=False)
>>> print(f"Nearest pair: A{stats['nearest_pair'][0] + 1}-A{stats['nearest_pair'][1] + 1}")