Skip to content

Plotting

plotting can be replaced by pl, e.g., concord.plotting.plot_embedding can be concord.pl.plot_embedding

concord.plotting.plot_embedding(adata, basis, color_by=None, pal=None, highlight_indices=None, default_color='lightgrey', highlight_color='black', highlight_size=20, highlight_density=False, density_color='viridis', density_levels=5, density_alpha=0.5, draw_path=False, alpha=0.9, text_alpha=0.5, figsize=(9, 3), dpi=300, ncols=1, ax=None, title=None, xlabel=None, ylabel=None, xticks=True, yticks=True, colorbar_loc='right', vmax_quantile=None, vmax=None, font_size=8, point_size=10, path_width=1, legend_loc='on data', rasterized=True, seed=42, save_path=None)

Plots a 2D embedding (e.g., UMAP, PCA) with optional highlighting and color mapping.

Parameters:

Name Type Description Default
adata AnnData

Single-cell AnnData object containing embeddings and metadata.

required
basis str

The name of the embedding stored in adata.obsm (e.g., 'X_umap').

required
color_by str | list

Column(s) in adata.obs to color the points by. Defaults to None.

None
pal dict

Color palette mapping category values to colors. Defaults to None.

None
highlight_indices list

Indices of points to highlight. Defaults to None.

None
default_color str

Default color for uncolored points. Defaults to "lightgrey".

'lightgrey'
highlight_color str

Color for highlighted points. Defaults to "black".

'black'
highlight_size int

Size of highlighted points. Defaults to 20.

20
draw_path bool

Whether to draw a path connecting highlighted points. Defaults to False.

False
alpha float

Opacity of points. Defaults to 0.9.

0.9
text_alpha float

Opacity of text labels. Defaults to 0.5.

0.5
figsize tuple

Figure size (width, height). Defaults to (9, 3).

(9, 3)
dpi int

Resolution of the figure. Defaults to 300.

300
ncols int

Number of columns for subplots. Defaults to 1.

1
ax Axes

Axes object for the plot. Defaults to None.

None
title str

Title of the plot. Defaults to None.

None
xlabel str

Label for X-axis. Defaults to None.

None
ylabel str

Label for Y-axis. Defaults to None.

None
xticks bool

Whether to show X-axis ticks. Defaults to True.

True
yticks bool

Whether to show Y-axis ticks. Defaults to True.

True
colorbar_loc str

Location of colorbar ("right", "left", "bottom", etc.). Defaults to "right".

'right'
vmax_quantile float

If provided, scales the color range to this quantile. Defaults to None.

None
vmax float

Maximum value for color scaling. Defaults to None.

None
font_size int

Font size for annotations. Defaults to 8.

8
point_size int

Size of scatter plot points. Defaults to 10.

10
path_width int

Width of path lines (if draw_path=True). Defaults to 1.

1
legend_loc str

Location of the legend ("on data", "right margin", etc.). Defaults to "on data".

'on data'
rasterized bool

If True, rasterizes the points for efficient plotting. Defaults to True.

True
seed int

Random seed for reproducibility. Defaults to 42.

42
save_path str

Path to save the figure. Defaults to None.

None

Returns:

Type Description

None

concord.plotting.plot_all_embeddings(adata, combined_keys, color_bys=['time', 'batch'], basis_types=['PAGA', 'KNN', 'PCA', 'UMAP'], pal={'time': 'viridis', 'batch': 'Set1'}, vmax_quantile=None, k=15, edges_color='grey', edges_width=0.05, layout='kk', threshold=0.1, node_size_scale=0.1, edge_width_scale=0.1, font_size=7, legend_font_size=2, point_size=2.5, alpha=0.8, figsize=(9, 0.9), ncols=11, seed=42, leiden_key='leiden', leiden_resolution=1.0, legend_loc=None, colorbar_loc=None, rasterized=True, save_dir='.', dpi=300, save_format='png', file_suffix='plot', highlight_indices=None, highlight_color='black', highlight_size=20, draw_path=False, path_width=1)

Plots multiple 2D embeddings (PAGA, KNN, PCA, UMAP) with different color mappings.

Parameters:

Name Type Description Default
adata AnnData

Single-cell AnnData object containing embeddings.

required
combined_keys list

List of feature representations (e.g., ['X_pca', 'X_umap']).

required
color_bys tuple

List of adata.obs columns to color by. Defaults to ("time", "batch").

['time', 'batch']
basis_types tuple

Types of embeddings to plot. Defaults to ("PAGA", "KNN", "PCA", "UMAP").

['PAGA', 'KNN', 'PCA', 'UMAP']
pal dict

Color palettes for each color_by variable. Defaults to {"time": "viridis", "batch": "Set1"}.

{'time': 'viridis', 'batch': 'Set1'}
vmax_quantile float

Upper quantile for color scaling in numeric data. Defaults to None.

None
k int

Number of neighbors for KNN and PAGA graphs. Defaults to 15.

15
edges_color str

Color of edges in KNN/PAGA graphs. Defaults to "grey".

'grey'
edges_width float

Width of edges in KNN/PAGA graphs. Defaults to 0.05.

0.05
layout str

Graph layout algorithm for KNN/PAGA. Defaults to "kk".

'kk'
threshold float

Edge threshold for PAGA visualization. Defaults to 0.1.

0.1
node_size_scale float

Scale factor for PAGA node sizes. Defaults to 0.1.

0.1
edge_width_scale float

Scale factor for PAGA edge widths. Defaults to 0.1.

0.1
font_size int

Font size for plot annotations. Defaults to 7.

7
legend_font_size int

Font size for legends. Defaults to 2.

2
point_size float

Size of scatter plot points. Defaults to 2.5.

2.5
alpha float

Transparency of points. Defaults to 0.8.

0.8
figsize tuple

Figure size (width, height). Defaults to (9, 0.9).

(9, 0.9)
ncols int

Number of columns for subplot grid. Defaults to 11.

11
seed int

Random seed for reproducibility. Defaults to 42.

42
leiden_key str

Key for Leiden clustering in PAGA. Defaults to "leiden".

'leiden'
leiden_resolution float

Resolution parameter for Leiden clustering. Defaults to 1.0.

1.0
legend_loc str

Location of the legend. Defaults to None.

None
colorbar_loc str

Location of the colorbar. Defaults to None.

None
rasterized bool

Whether to rasterize the plot. Defaults to True.

True
save_dir str

Directory to save plots. Defaults to ".".

'.'
dpi int

Image resolution. Defaults to 300.

300
save_format str

Image format ("png", "pdf", etc.). Defaults to "png".

'png'
file_suffix str

Filename suffix. Defaults to "plot".

'plot'
highlight_indices list

Indices of highlighted points. Defaults to None.

None
highlight_color str

Color of highlighted points. Defaults to "black".

'black'
highlight_size int

Size of highlighted points. Defaults to 20.

20
draw_path bool

Whether to draw a connecting path for highlights. Defaults to False.

False
path_width int

Width of connecting paths. Defaults to 1.

1

Returns:

Type Description

None

concord.plotting.plot_embedding_3d(adata, basis='encoded_UMAP', color_by='batch', pal=None, save_path=None, point_size=3, opacity=0.7, seed=42, width=800, height=600, engine='plotly', autosize=True, static=False, static_format='png')

Plots a 3D embedding using Plotly or Matplotlib.

Parameters:

Name Type Description Default
adata AnnData

Single-cell AnnData object containing embeddings.

required
basis str

The name of the 3D embedding stored in adata.obsm. Defaults to 'encoded_UMAP'.

'encoded_UMAP'
color_by str

Column in adata.obs used to color points. Defaults to 'batch'.

'batch'
pal dict

Color palette mapping categorical variables to colors. Defaults to None.

None
save_path str

Path to save the figure. Defaults to None.

None
point_size int

Size of the points in the plot. Defaults to 3.

3
opacity float

Opacity of the points. Defaults to 0.7.

0.7
seed int

Random seed for reproducibility. Defaults to 42.

42
width int

Width of the plot in pixels. Defaults to 800.

800
height int

Height of the plot in pixels. Defaults to 600.

600
engine str

Rendering engine ('plotly' or 'matplotlib'). Defaults to 'plotly'.

'plotly'
autosize bool

Whether to automatically adjust plot size. Defaults to True.

True
static bool

If True, saves the plot as a static image. Defaults to False.

False
static_format str

Format for static image (e.g., 'png', 'pdf'). Defaults to 'png'.

'png'

Returns:

Type Description

plotly.Figure or matplotlib.Figure: A 3D scatter plot.

Raises:

Type Description
ValueError

If the engine is not 'plotly' or 'matplotlib'.

concord.plotting.plot_all_embeddings_3d(adata, combined_keys, color_bys=('time', 'batch'), basis_types=('UMAP_3D',), pal=None, point_size=2.5, alpha=0.8, figsize=(10, 5), ncols=4, seed=42, legend_font_size=5, rasterized=False, save_dir='.', dpi=300, save_format='png', file_suffix='3d_plot', elev=30, azim=45, zoom_factor=0.0, **kwargs)

Plots multiple 3D embeddings with different color mappings across various embedding types.

Each subplot represents a different embedding (e.g., UMAP_3D) with a specified coloring (e.g., time, batch). This function generates a grid of 3D scatter plots.

Parameters:

Name Type Description Default
adata AnnData

Single-cell AnnData object containing embeddings.

required
combined_keys list

List of feature representations for which embeddings exist in adata.obsm.

required
color_bys tuple of str

List of adata.obs columns to color points by. Defaults to ('time', 'batch').

('time', 'batch')
basis_types tuple of str

Types of embeddings to plot. Defaults to ('UMAP_3D',).

('UMAP_3D',)
pal dict

Dictionary mapping categorical values to colors. Defaults to None.

None
point_size float

Size of points in the scatter plot. Defaults to 2.5.

2.5
alpha float

Opacity of points. Defaults to 0.8.

0.8
figsize tuple

Figure size in inches (width, height). Defaults to (10, 5).

(10, 5)
ncols int

Number of columns in the subplot grid. Defaults to 4.

4
seed int

Random seed for color mapping. Defaults to 42.

42
legend_font_size int

Font size for legend labels. Defaults to 5.

5
rasterized bool

Whether to rasterize the scatter plots to reduce file size. Defaults to False.

False
save_dir str

Directory where plots will be saved. Defaults to '.'.

'.'
dpi int

Image resolution in dots per inch. Defaults to 300.

300
save_format str

Image format ('png', 'pdf', 'svg', etc.). Defaults to 'png'.

'png'
file_suffix str

Suffix to append to saved file names. Defaults to '3d_plot'.

'3d_plot'
elev float

Elevation angle for 3D view. Defaults to 30.

30
azim float

Azimuth angle for 3D view. Defaults to 45.

45
zoom_factor float

Zoom factor to adjust the scale of the plot. Defaults to 0.0.

0.0
**kwargs

Additional parameters forwarded to plot_embedding_3d_matplotlib for customization.

{}

Returns:

Name Type Description
None

Saves one figure per (basis_type, color_by) combination.

Raises:

Type Description
ValueError

If a specified basis_type is not found

concord.plotting.plot_rotating_embedding_3d_to_mp4(adata, embedding_key='encoded_UMAP', color_by='batch', save_path='rotation.mp4', pal=None, point_size=3, opacity=0.7, width=800, height=1200, rotation_duration=10, num_steps=60, legend_itemsize=100, font_size=16, seed=42)

Generates a rotating 3D embedding animation and saves it as an MP4 video.

This function visualizes a 3D embedding (e.g., UMAP, PCA) with an animated rotation and saves it as an MP4 video. The colors can be mapped to different cell metadata.

Parameters:

Name Type Description Default
adata AnnData

Single-cell AnnData object containing embeddings and metadata.

required
embedding_key str

Key in adata.obsm where the 3D embedding is stored. Defaults to 'encoded_UMAP'.

'encoded_UMAP'
color_by str

Column in adata.obs to color points by. Defaults to 'batch'.

'batch'
save_path str

File path to save the MP4 video. Defaults to 'rotation.mp4'.

'rotation.mp4'
pal dict

Color palette mapping categorical values to colors. Defaults to None.

None
point_size int

Size of the scatter plot points. Defaults to 3.

3
opacity float

Opacity of the scatter plot points. Defaults to 0.7.

0.7
width int

Width of the output video in pixels. Defaults to 800.

800
height int

Height of the output video in pixels. Defaults to 1200.

1200
rotation_duration int

Duration of the rotation animation in seconds. Defaults to 10.

10
num_steps int

Number of frames used for the rotation. Higher values result in a smoother animation. Defaults to 60.

60
legend_itemsize int

Size of legend markers for categorical color mappings. Defaults to 100.

100
font_size int

Font size for legends and labels. Defaults to 16.

16
seed int

Random seed for color mapping. Defaults to 42.

42

Returns:

Name Type Description
None

Saves the rotating animation as an MP4 file.

Raises:

Type Description
KeyError

If embedding_key is not found in adata.obsm or color_by is not in adata.obs.

ValueError

If the specified embedding has fewer than 3 dimensions.

Example
plot_rotating_embedding_3d_to_mp4(
    adata,
    embedding_key='X_umap',
    color_by='cell_type',
    save_path='3D_rotation.mp4',
    rotation_duration=15,
    num_steps=90
)

concord.plotting.heatmap_with_annotations(adata, val, transpose=True, obs_keys=None, cmap='viridis', vmin=None, vmax=None, cluster_rows=True, cluster_cols=True, pal=None, add_color_legend=False, value_annot=False, title=None, title_fontsize=16, annot_fontsize=8, yticklabels=True, xticklabels=False, use_clustermap=True, cluster_method='ward', cluster_metric='euclidean', rasterize=True, ax=None, figsize=(12, 8), seed=42, dpi=300, show=True, save_path=None)

Creates a heatmap colored by multiple columns in adata.obs, optionally clusters the rows/columns, and provides categorical or continuous annotations.

Parameters:

Name Type Description Default
adata AnnData

AnnData object containing the dataset.

required
val str | ndarray | DataFrame

Data source for heatmap. Can be: - 'X': Uses adata.X - A layer name from adata.layers - An embedding from adata.obsm - A numpy.ndarray or pandas.DataFrame

required
transpose bool

If True, transposes the data matrix. Defaults to True.

True
obs_keys list

List of column names in adata.obs to use for categorical or numerical coloring. Defaults to None.

None
cmap str

Colormap for heatmap values. Defaults to 'viridis'.

'viridis'
vmin float

Minimum value for color scaling. Defaults to None.

None
vmax float

Maximum value for color scaling. Defaults to None.

None
cluster_rows bool

Whether to cluster rows. Defaults to True.

True
cluster_cols bool

Whether to cluster columns. Defaults to True.

True
pal dict

Dictionary mapping category values to colors. Defaults to None.

None
add_color_legend bool

If True, adds a legend for categorical annotations. Defaults to False.

False
value_annot bool

If True, annotates each heatmap cell with values. Defaults to False.

False
title str

Title of the heatmap. Defaults to None.

None
title_fontsize int

Font size for title. Defaults to 16.

16
annot_fontsize int

Font size for annotations (if value_annot=True). Defaults to 8.

8
yticklabels bool

Whether to show row labels. Defaults to True.

True
xticklabels bool

Whether to show column labels. Defaults to False.

False
use_clustermap bool

If True, uses seaborn.clustermap for hierarchical clustering. Otherwise, uses sns.heatmap. Defaults to True.

True
cluster_method str

Clustering method for hierarchical clustering (e.g., 'ward', 'average', 'single'). Defaults to 'ward'.

'ward'
cluster_metric str

Distance metric for hierarchical clustering (e.g., 'euclidean', 'correlation'). Defaults to 'euclidean'.

'euclidean'
rasterize bool

If True, rasterizes heatmap elements for efficient plotting. Defaults to True.

True
ax Axes

Matplotlib Axes object to plot on. Defaults to None.

None
figsize tuple

Size of the figure (width, height). Defaults to (12, 8).

(12, 8)
seed int

Random seed for reproducibility. Defaults to 42.

42
dpi int

Resolution of the saved figure. Defaults to 300.

300
show bool

If True, displays the plot. Defaults to True.

True
save_path str

Path to save the figure. If None, the figure is not saved. Defaults to None.

None

Returns:

Type Description

matplotlib.Axes | seaborn.ClusterGrid: - If use_clustermap=True, returns a seaborn.ClusterGrid object. - Otherwise, returns a matplotlib.Axes object.

concord.plotting.plot_benchmark_table(df, pal='PRGn', pal_agg='YlGnBu', cmap_method='norm', cmap_padding=0.05, agg_name='Aggregate score', dpi=300, save_path=None, figsize=None)

Plots a benchmarking results table using the plottable library.

This function creates a formatted table displaying different benchmarking metrics across various methods. It includes: - Circle-marked metric values. - Color-encoded values based on a chosen colormap. - Aggregate scores visualized as bar charts.

Parameters:

Name Type Description Default
df DataFrame

The benchmarking results DataFrame. It should have a multi-index in columns where the first level represents metric categories and the second level contains metric names.

required
pal str

Colormap for individual metric values. Defaults to 'PRGn'.

'PRGn'
pal_agg str

Colormap for aggregate scores. Defaults to 'YlGnBu'.

'YlGnBu'
cmap_method str

Method for normalizing colormaps. Options: - 'norm': Normalize based on standard deviation. - 'minmax': Normalize based on the min-max range. - 'minmax_padded': Adds padding to the min-max normalization. - '0_to_1': Normalize between 0 and 1. Defaults to 'norm'.

'norm'
cmap_padding float

Padding factor for minmax_padded colormap normalization. Defaults to 0.05.

0.05
agg_name str

The name of the aggregate score column. Defaults to 'Aggregate score'.

'Aggregate score'
dpi int

Resolution of the saved figure. Defaults to 300.

300
save_path str

If provided, saves the figure to the specified path. Defaults to None.

None
figsize tuple

Figure size (width, height). If None, it is determined dynamically based on the number of columns and rows. Defaults to None.

None

Raises:

Type Description
ValueError

If cmap_method is not one of 'norm', 'minmax', 'minmax_padded', or '0_to_1'.

Returns:

Type Description

None

concord.plotting.plot_adata_layer_heatmaps(adata, ncells=None, ngenes=None, layers=['X_concord_decoded', 'X_log1p'], transpose=False, obs_keys=None, cluster_rows=False, cluster_cols=False, use_clustermap=False, seed=0, figsize=(6, 6), cmap='viridis', dpi=300, vmin=None, vmax=None, save_path=None)

Plots heatmaps of selected layers from an AnnData object, optionally clustering rows and columns.

This function visualizes gene expression data from different layers of an AnnData object as heatmaps. It allows for subsampling of cells and genes, clustering of rows and columns, and saving the output figure.

Parameters:

Name Type Description Default
adata AnnData

The AnnData object containing gene expression data.

required
ncells int

Number of cells to subsample. If None, uses all cells. Defaults to None.

None
ngenes int

Number of genes to subsample. If None, uses all genes. Defaults to None.

None
layers list of str

List of layer names to plot heatmaps for. Defaults to ['X_concord_decoded', 'X_log1p'].

['X_concord_decoded', 'X_log1p']
transpose bool

If True, transposes the heatmap (genes as columns). Defaults to False.

False
obs_keys list of str

List of categorical metadata columns from adata.obs to annotate along heatmap axes. Defaults to None.

None
cluster_rows bool

Whether to cluster rows (genes). Defaults to False.

False
cluster_cols bool

Whether to cluster columns (cells). Defaults to False.

False
use_clustermap bool

If True, uses seaborn.clustermap instead of sns.heatmap for hierarchical clustering. Defaults to False.

False
seed int

Random seed for reproducibility in subsampling. Defaults to 0.

0
figsize tuple

Figure size (width, height). Defaults to (6, 6).

(6, 6)
cmap str

Colormap for the heatmap. Defaults to 'viridis'.

'viridis'
dpi int

Resolution of the saved figure. Defaults to 300.

300
vmin float

Minimum value for heatmap normalization. Defaults to None.

None
vmax float

Maximum value for heatmap normalization. Defaults to None.

None
save_path str

If provided, saves the heatmap figure to the specified path. Defaults to None.

None

Raises:

Type Description
ValueError

If ncells or ngenes is greater than the dimensions of adata.

ValueError

If a specified layer is not found in adata.layers.

Returns:

Type Description

None Displays the heatmaps and optionally saves the figure.

Example
plot_adata_layer_heatmaps(adata, ncells=500, ngenes=100, layers=['X', 'X_log1p'],
                          cluster_rows=True, cluster_cols=True, use_clustermap=True,
                          save_path="heatmap.png")

concord.plotting.visualize_importance_weights(model, adata, top_n=20, mode='histogram', fontsize=12, figsize=(5, 3), save_path=None)

Visualizes feature importance weights from a trained model.

This function plots either a histogram of all importance weights or a bar chart of the top features based on their importance values.

Parameters:

Name Type Description Default
model Module

The trained model containing feature importance weights.

required
adata AnnData

The AnnData object containing gene expression data.

required
top_n int

Number of top features to plot when mode is not 'histogram'. Defaults to 20.

20
mode str

Visualization mode. Options: - 'histogram': Plots the distribution of all importance weights. - 'highest': Shows top top_n features with highest importance. - 'lowest': Shows top_n features with lowest importance. - 'absolute': Shows top_n features with highest absolute importance. Defaults to 'histogram'.

'histogram'
fontsize int

Font size for axis labels and titles. Defaults to 12.

12
figsize tuple

Figure size (width, height). Defaults to (5, 3).

(5, 3)
save_path str

If provided, saves the figure at the specified path. Defaults to None.

None

Raises:

Type Description
ValueError

If mode is not one of 'histogram', 'highest', 'lowest', 'absolute'.

Returns:

Type Description

None Displays or saves the importance weights plot.

Example
visualize_importance_weights(model, adata, mode='highest', top_n=30)

concord.plotting.plot_importance_heatmap(importance_matrix, input_feature=None, figsize=(20, 15), save_path=None)

Plots a heatmap of feature importance across encoded neurons.

This function visualizes the importance of each input feature for different encoded neurons using hierarchical clustering.

Parameters:

Name Type Description Default
importance_matrix ndarray or Tensor

The importance matrix with shape (n_input_features, n_encoded_neurons).

required
input_feature list of str

List of input feature names (e.g., gene names). If None, generic feature names are used.

None
figsize tuple

Figure size (width, height). Defaults to (20, 15).

(20, 15)
save_path str

If provided, saves the heatmap at the specified path. Defaults to None.

None

Returns:

Type Description

None Displays or saves the importance heatmap.

Example
plot_importance_heatmap(importance_matrix, input_feature=adata.var_names)

concord.plotting.plot_top_genes_per_neuron(ranked_gene_lists, show_neurons=None, top_n=10, ncols=4, figsize=(4, 4), save_path=None)

Plots bar charts of the top contributing genes for each neuron.

This function generates bar plots showing the most important genes contributing to each encoded neuron in a compact grid layout.

Parameters:

Name Type Description Default
ranked_gene_lists dict

Dictionary where keys are neuron names and values are DataFrames containing ranked genes.

required
show_neurons list

List of neurons to plot. If None, plots all neurons available in ranked_gene_lists. Defaults to None.

None
top_n int

Number of top contributing genes to display for each neuron. Defaults to 10.

10
ncols int

Number of columns in the subplot grid. Defaults to 4.

4
figsize tuple

Size of each subplot (width, height). Defaults to (4, 4).

(4, 4)
save_path str

If provided, saves the plot at the specified path. Defaults to None.

None

Returns:

Type Description

None Displays or saves the bar charts.

Example
plot_top_genes_per_neuron(ranked_gene_lists, top_n=15, ncols=3, save_path="top_genes.png")

concord.plotting.get_color_mapping(adata, col, pal, seed=42)

Generates a color mapping for a given column in adata.obs or for gene expression.

This function determines whether the column is numeric or categorical and assigns an appropriate colormap (for numeric data) or a categorical color palette.

Parameters:

Name Type Description Default
adata AnnData

An AnnData object containing single-cell expression data.

required
col str

The column in adata.obs or a gene name in adata.var_names to be used for coloring.

required
pal dict, str, or None

Color palette or colormap for categorical or numeric data. - If dict, it should map categories to colors. - If str, it should be a recognized seaborn or matplotlib palette/colormap. - If None, defaults to 'Set1' for categorical data and 'viridis' for numeric data.

required
seed int

Random seed for reproducibility when shuffling colors in categorical mapping. Defaults to 42.

42

Returns:

Name Type Description
tuple

(data_col, cmap, palette) - data_col (pd.Series or np.ndarray): The extracted column data from adata.obs or adata[:, col].X. - cmap (matplotlib.colors.Colormap or None): A colormap for numeric data. Returns None for categorical data. - palette (dict or None): A dictionary mapping categorical values to colors. Returns None for numeric data.

Raises:

Type Description
ValueError

If the column is neither found in adata.obs nor in adata.var_names.

ValueError

If a numeric column is provided with a categorical palette (dict).

Example
data_col, cmap, palette = get_color_mapping(adata, 'batch', pal='Set2')
data_col, cmap, palette = get_color_mapping(adata, 'GeneX', pal='RdYlBu')

concord.plotting.plot_go_enrichment(gp_results, top_n=10, qval_correct=1e-10, color_palette='viridis_r', font_size=12, figsize=(7, 3), dpi=300, save_path=None)

Plots the top Gene Ontology (GO) enrichment terms based on adjusted p-values (FDR q-values).

Parameters:

Name Type Description Default
gp_results object

GO enrichment results object containing a DataFrame in gp_results.results.

required
top_n int

Number of top terms to display. Defaults to 10.

10
qval_correct float

A small correction factor added to q-values before taking -log10. Defaults to 1e-10.

1e-10
color_palette str

Color palette for the bar plot. Defaults to 'viridis_r'.

'viridis_r'
font_size int

Font size for plot labels. Defaults to 12.

12
figsize tuple

Size of the figure in inches (width, height). Defaults to (7,3).

(7, 3)
dpi int

Dots per inch (resolution) for saving the figure. Defaults to 300.

300
save_path str

File path to save the figure. If None, the figure is displayed instead of being saved. Defaults to None.

None

Returns:

Type Description

None

Example
plot_go_enrichment(gp_results, top_n=15, save_path="go_enrichment.png")

concord.plotting.plot_all_top_enriched_terms(all_gsea_results, top_n=10, ncols=1, font_size=10, color_palette='viridis_r', qval_correct=1e-10, figsize=(4, 4), dpi=300, save_path=None)

Plots the top enriched Gene Set Enrichment Analysis (GSEA) terms for multiple neurons.

Parameters:

Name Type Description Default
all_gsea_results dict

Dictionary where keys are neuron names and values are GSEA results DataFrames.

required
top_n int

Number of top enriched terms to display per neuron. Defaults to 10.

10
ncols int

Number of columns in the subplot grid layout. Defaults to 1.

1
font_size int

Font size for plot labels. Defaults to 10.

10
color_palette str

Color palette for the bar plots. Defaults to 'viridis_r'.

'viridis_r'
qval_correct float

A small correction factor added to q-values before taking -log10. Defaults to 1e-10.

1e-10
figsize tuple

Size of each subplot (width, height) in inches. Defaults to (4,4).

(4, 4)
dpi int

Resolution of the output figure. Defaults to 300.

300
save_path str

File path to save the figure. If None, the figure is displayed. Defaults to None.

None

Returns:

Type Description

None

Example
plot_all_top_enriched_terms(all_gsea_results, top_n=5, ncols=2, save_path="gsea_terms.pdf")

concord.plotting.plot_all_top_gsea_results(all_gsea_results, terms_per_plot=5, ncols=4, figsize_per_plot=(3, 4), dpi=300, save_path=None)

Plots Gene Set Enrichment Analysis (GSEA) results for multiple neurons in a grid layout.

Parameters:

Name Type Description Default
all_gsea_results dict

Dictionary where keys are neuron names and values are GSEA result objects.

required
terms_per_plot int

Number of top enriched terms to display per neuron. Defaults to 5.

5
ncols int

Number of columns in the subplot grid. Defaults to 4.

4
figsize_per_plot tuple

Size of each subplot (width, height) in inches. Defaults to (3,4).

(3, 4)
dpi int

Resolution of the output figure in dots per inch. Defaults to 300.

300
save_path str

File path to save the figure. If None, the figure is displayed. Defaults to None.

None

Returns:

Type Description

None

Example
plot_all_top_gsea_results(all_gsea_results, terms_per_plot=7, ncols=3, save_path="gsea_results.png")

concord.plotting.plot_trustworthiness(trustworthiness_df, text_label=True, text_shift=1, legend=False, fontsize=8, legend_fontsize=8, figsize=(6, 4), dpi=300, save_path=None)

Plots trustworthiness scores for different latent embeddings over a range of neighborhood sizes.

Parameters:

Name Type Description Default
trustworthiness_df DataFrame

DataFrame containing columns Embedding, n_neighbors, and Trustworthiness.

required
text_label bool

Whether to display text labels for the last data point of each embedding. Defaults to True.

True
text_shift float

Horizontal shift applied to text labels for readability. Defaults to 1.

1
legend bool

Whether to show a legend on the right. Defaults to False.

False
fontsize int

Font size for plot labels. Defaults to 8.

8
legend_fontsize int

Font size for legend text. Defaults to 8.

8
figsize tuple

Figure size in inches (width, height). Defaults to (6, 4).

(6, 4)
dpi int

Resolution (dots per inch) for saving the figure. Defaults to 300.

300
save_path str

File path to save the figure. If None, the plot is displayed instead. Defaults to None.

None

Returns:

Type Description

None

Example
plot_trustworthiness(trustworthiness_df, legend=True, save_path="trustworthiness_plot.png")

concord.plotting.plot_distance_heatmap(distances, n_cols=3, annot_value=False, figsize=(2, 1.6), cbar=True, fontsize=10, rasterize=True, dpi=300, save_path=None)

Plots heatmaps of pairwise distance matrices in a grid layout.

Parameters:

Name Type Description Default
distances dict

Dictionary where keys are distance metric names and values are distance matrices.

required
n_cols int

Number of columns in the subplot grid. Defaults to 3.

3
annot_value bool

Whether to annotate heatmap values. Defaults to False.

False
figsize tuple

Base figure size for each subplot (width, height). Defaults to (2, 1.6).

(2, 1.6)
cbar bool

Whether to display a color bar. Defaults to True.

True
fontsize int

Font size for axis labels and titles. Defaults to 10.

10
rasterize bool

Whether to rasterize the heatmap for better performance. Defaults to True.

True
dpi int

Resolution (dots per inch) for saving the figure. Defaults to 300.

300
save_path str

File path to save the figure. If None, the plot is displayed instead. Defaults to None.

None

Returns:

Type Description

None

Example
plot_distance_heatmap(distances, n_cols=4, save_path="distance_heatmaps.png")

concord.plotting.plot_geometry_scatter(data_dict, correlation=None, ground_key='PCA_no_noise', linear_fit=False, s=1, c=None, alpha=0.5, n_cols=3, fontsize=8, figsize=(4, 4), rasterized=True, dpi=300, save_path=None)

Plots scatter plots comparing geometric properties of embeddings.

Parameters:

Name Type Description Default
data_dict dict

Dictionary where keys are embedding names and values are distance vectors.

required
correlation DataFrame

DataFrame containing correlation values for each embedding. Defaults to None.

None
ground_key str

Key used as the reference ground-truth embedding. Defaults to 'PCA_no_noise'.

'PCA_no_noise'
linear_fit bool

Whether to fit and plot a linear regression line. Defaults to False.

False
s float

Marker size in scatter plots. Defaults to 1.

1
c str or array - like

Color of points. Defaults to None.

None
alpha float

Opacity of points. Defaults to 0.5.

0.5
n_cols int

Number of columns in the subplot grid. Defaults to 3.

3
fontsize int

Font size for axis labels and titles. Defaults to 8.

8
figsize tuple

Base figure size for each subplot (width, height). Defaults to (4, 4).

(4, 4)
rasterized bool

Whether to rasterize scatter points for performance. Defaults to True.

True
dpi int

Resolution (dots per inch) for saving the figure. Defaults to 300.

300
save_path str

File path to save the figure. If None, the plot is displayed instead. Defaults to None.

None

Returns:

Type Description

None

Example
plot_geometry_scatter(data_dict, correlation=correlation_df, save_path="geometry_scatter.png")

concord.plotting.plot_persistence_diagram(diagram, homology_dimensions=None, ax=None, show=True, legend=True, legend_loc='lower right', label_axes=True, colormap='tab10', marker_size=20, diagonal=True, title=None, fontsize=12, axis_ticks=True, xlim=None, ylim=None, rasterized=True)

Plots a persistence diagram showing birth and death times of topological features.

Parameters:

Name Type Description Default
diagram array - like

Persistence diagram data (birth, death, homology dimension).

required
homology_dimensions list

Homology dimensions to plot (e.g., [0, 1, 2]). Defaults to all available.

None
ax Axes

Matplotlib axis to plot on. If None, a new figure is created.

None
show bool

Whether to display the plot. Defaults to True.

True
legend bool

Whether to show a legend. Defaults to True.

True
legend_loc str

Location of the legend. Defaults to 'lower right'.

'lower right'
label_axes bool

Whether to label the x- and y-axes. Defaults to True.

True
colormap str

Colormap for different homology dimensions. Defaults to 'tab10'.

'tab10'
marker_size int

Size of markers for points. Defaults to 20.

20
diagonal bool

Whether to plot the diagonal y = x reference line. Defaults to True.

True
title str

Title of the plot. Defaults to None.

None
fontsize int

Font size for labels and title. Defaults to 12.

12
axis_ticks bool

Whether to display axis ticks. Defaults to True.

True
xlim tuple

Limits for the x-axis. Defaults to None.

None
ylim tuple

Limits for the y-axis. Defaults to None.

None
rasterized bool

Whether to rasterize the plot for performance. Defaults to True.

True

Returns:

Type Description

matplotlib.axes.Axes: The axis object containing the persistence diagram.

Example
plot_persistence_diagram(diagram, homology_dimensions=[0, 1])

concord.plotting.plot_persistence_diagrams(diagrams, marker_size=4, n_cols=3, dpi=300, base_size=(3, 3), legend=True, legend_loc=None, rasterized=True, fontsize=12, save_path=None, **kwargs)

Plots multiple persistence diagrams in a grid layout.

Parameters:

Name Type Description Default
diagrams dict

Dictionary where keys are dataset names and values are persistence diagrams.

required
marker_size int

Size of markers for points. Defaults to 4.

4
n_cols int

Number of columns in the grid. Defaults to 3.

3
dpi int

Resolution of the figure. Defaults to 300.

300
base_size tuple

Base figure size for each subplot (width, height). Defaults to (3, 3).

(3, 3)
legend bool

Whether to include legends. Defaults to True.

True
legend_loc str

Location of the legend. Defaults to None.

None
rasterized bool

Whether to rasterize the plots. Defaults to True.

True
fontsize int

Font size for labels and titles. Defaults to 12.

12
save_path str

File path to save the figure. Defaults to None.

None

Returns:

Type Description

None

Example
plot_persistence_diagrams(diagrams, n_cols=2, save_path="persistence_diagrams.png")

concord.plotting.plot_betti_curve(diagram, nbins=100, homology_dimensions=[0, 1, 2], title='Betti curves', ymax=10, ax=None, show=True, legend=True, legend_loc='upper right', label_axes=True, axis_ticks=True, fontsize=12)

Plots Betti curves, which track the number of topological features over filtration values.

Parameters:

Name Type Description Default
diagram array - like

Persistence diagram data used to compute Betti curves.

required
nbins int

Number of bins for filtration values. Defaults to 100.

100
homology_dimensions list

List of homology dimensions to plot. Defaults to [0, 1, 2].

[0, 1, 2]
title str

Title of the plot. Defaults to "Betti curves".

'Betti curves'
ymax int

Maximum y-axis value. Defaults to 10.

10
ax Axes

Axis object for plotting. If None, a new figure is created.

None
show bool

Whether to display the plot. Defaults to True.

True
legend bool

Whether to include a legend. Defaults to True.

True
legend_loc str

Location of the legend. Defaults to 'upper right'.

'upper right'
label_axes bool

Whether to label the axes. Defaults to True.

True
axis_ticks bool

Whether to include axis ticks. Defaults to True.

True
fontsize int

Font size for labels and title. Defaults to 12.

12

Returns:

Type Description

matplotlib.axes.Axes: The axis object containing the Betti curve.

Example
plot_betti_curve(diagram, nbins=50, homology_dimensions=[0,1])

concord.plotting.plot_betti_curves(diagrams, nbins=100, ymax=8, n_cols=3, base_size=(3, 3), dpi=300, legend=True, save_path=None, **kwargs)

Plots Betti curves for multiple persistence diagrams in a grid layout.

Parameters

diagrams : dict A dictionary where keys are diagram names and values are persistence diagrams. nbins : int, optional Number of bins to use for Betti curve computation, by default 100. ymax : int, optional Maximum y-axis limit for the Betti curves, by default 8. n_cols : int, optional Number of columns in the grid layout, by default 3. base_size : tuple, optional Base figure size (width, height) for each subplot, by default (3,3). dpi : int, optional Dots per inch for figure resolution, by default 300. legend : bool, optional Whether to include a legend in each plot, by default True. save_path : str, optional File path to save the plot. If None, the plot is displayed instead. **kwargs : dict Additional keyword arguments passed to plot_betti_curve.

Returns

None Displays or saves the plotted figure.

Notes

Each subplot corresponds to a Betti curve computed from a persistence diagram.

concord.plotting.plot_betti_statistic(betti_stats_pivot, statistic='Entropy', dimension=None, log_y=False, bar_width=0.2, pal='tab20', figsize=(7, 4), dpi=300, save_path=None, xlabel_fontsize=8, ylabel_fontsize=8, tick_fontsize=7, title_fontsize=9, legend_fontsize=8)

Plots a grouped bar chart of Betti number statistics across different methods.

Parameters:

Name Type Description Default
betti_stats_pivot DataFrame

DataFrame containing Betti number statistics.

required
statistic str

Statistic to plot (e.g., 'Entropy', 'Variance'). Defaults to 'Entropy'.

'Entropy'
dimension str or int

Specific homology dimension to plot. Defaults to None (plots all).

None
log_y bool

Whether to use a logarithmic scale on the y-axis. Defaults to False.

False
bar_width float

Width of bars in the grouped bar chart. Defaults to 0.2.

0.2
pal str

Color palette. Defaults to 'tab20'.

'tab20'
figsize tuple

Figure size in inches. Defaults to (7, 4).

(7, 4)
dpi int

Resolution in dots per inch. Defaults to 300.

300
save_path str

Path to save the figure. Defaults to None.

None

Returns:

Type Description

None

Example
plot_betti_statistic(betti_stats_df, statistic='Entropy', save_path="betti_statistic.png")

concord.plotting.plot_betti_distance(distance_metrics_df, metric, color='teal', log_y=False, figsize=(6, 4), dpi=300, save_path=None)

Plots distance metrics for Betti numbers across different methods.

Parameters:

Name Type Description Default
distance_metrics_df DataFrame

DataFrame containing distance metrics.

required
metric str

Metric to plot ('L1 Distance', 'L2 Distance', 'Total Relative Error').

required
color str

Color of the bars in the plot. Defaults to 'teal'.

'teal'
log_y bool

Whether to use a logarithmic scale on the y-axis. Defaults to False.

False
figsize tuple

Figure size in inches. Defaults to (6, 4).

(6, 4)
dpi int

Resolution in dots per inch. Defaults to 300.

300
save_path str

File path to save the plot. Defaults to None.

None

Returns:

Type Description

None

Example
plot_betti_distance(distance_metrics_df, metric="L1 Distance")