API Reference

Contents

API Reference#

Configuration#

class scplotkit.PlotConfig(data=None)[source]#

Bases: object

Holds styling and palette configuration for scplotkit plots.

Parameters:

data (dict[str, Any] | None) – Nested dict of configuration values. Merged on top of the built-in defaults, so you only need to specify what you want to override.

classmethod default()[source]#

Return a config with only the built-in, domain-agnostic defaults.

Return type:

PlotConfig

classmethod from_yaml(path)[source]#

Load a config from a YAML file, merged on top of the defaults.

Return type:

PlotConfig

Parameters:

path (str | Path)

property general: dict#
get(key, default=None)[source]#
Return type:

Any

Parameters:
  • key (str)

  • default (Any)

classmethod load(config)[source]#

Coerce a config-like value (config, dict, path, or None) into a PlotConfig.

Return type:

PlotConfig

Parameters:

config (PlotConfig | dict | str | Path | None)

palette_for(column)[source]#

Return the user-supplied color mapping for a column, if any.

Return type:

dict[str, str] | None

Parameters:

column (str)

property palettes: dict#
to_dict()[source]#
Return type:

dict

ScPlotter (convenience class)#

class scplotkit.ScPlotter(config=None, output_dir='figures')[source]#

Bases: object

Stateful convenience wrapper that remembers your config and output directory.

Every method mirrors a function of the same name in the corresponding scplotkit submodule (embeddings, composition, overview, markers, sankey) and simply forwards to it with config and output_dir pre-filled. Prefer calling the module functions directly if you don’t need the shared state.

Examples

>>> plotter = ScPlotter(output_dir="figures")
>>> plotter.masked_umap(adata, color_by="cell_type", figure_name="T cells",
...                      mask_values=["CD4 T", "CD8 T"])
Parameters:
  • config (PlotConfig | dict | str | Path | None)

  • output_dir (str | Path)

abundance_bubble_grid(adata, **kwargs)[source]#
annotation_marker_matrixplot(adata, markers_dict, groupby_column, **kwargs)[source]#
annotation_marker_stacked_violin(adata, markers_dict, groupby_column, **kwargs)[source]#
cell_abundance_barplot(adata, **kwargs)[source]#
cells_per_patient_boxplot(adata, **kwargs)[source]#
compare_cell_abundance_barplot(adata1, adata2, **kwargs)[source]#
compare_cell_abundance_boxplot(adata1, adata2, **kwargs)[source]#
composition_heatmap(adata, **kwargs)[source]#
embedding_density(adata, **kwargs)[source]#
gene_coexpression_umap(adata, **kwargs)[source]#
gene_expression_umap(adata, **kwargs)[source]#
masked_umap(adata, **kwargs)[source]#
masked_umap_highlight(adata, **kwargs)[source]#
ora_dotplot(csv_path, **kwargs)[source]#
pseudobulk_boxplot(adata, **kwargs)[source]#
pseudobulk_multigene_boxplot(adata, **kwargs)[source]#
rank_genes_matrix_and_dot(adata, groupby_column, **kwargs)[source]#
ridgeline_plot(adata, **kwargs)[source]#
sample_and_cell_counts_barplot(adata, **kwargs)[source]#
sample_and_cell_counts_barplot_break_axis(adata, **kwargs)[source]#
sankey_plot(adata, levels, **kwargs)[source]#
stacked_barplots(adata, **kwargs)[source]#
stacked_barplots_multi_meta(adata, **kwargs)[source]#
sunburst_plot(adata, levels, **kwargs)[source]#
treemap_plot(adata, levels, **kwargs)[source]#

scplotkit.embeddings#

Masked and highlighted UMAP (or any 2D embedding) plots.

These highlight a subset of cells (e.g. one lineage) against the rest of an atlas, which is a common need when illustrating where a population of interest sits within a larger dataset.

scplotkit.embeddings.embedding_density(adata, groupby=None, groups=None, figure_name=None, basis='umap', grid_size=200, bw_scale=0.5, density_threshold=0.01, cmap='YlOrBr', point_size=None, grey_color=None, grey_alpha=1.0, ncols=4, panel_size=(4.5, 4.5), key_added=None, config=None, output_dir='figures', save_name='embedding_density', show=False)[source]#

Fancy, fast per-cell density plot over an embedding, optionally per group.

Every cell is drawn as a dot and every dot is filled in – colored smoothly and continuously by its local density (no discrete contour bands, no outline layer sitting on top, nothing colored outside of where cells actually are): cells below density_threshold are flat grey (no signal there), the rest are colored along cmap by how dense the embedding is at that exact point. When groupby is given, one independently-scaled panel is drawn per category, on shared axis limits so panels stay visually comparable – each panel colors every cell by that category’s density field, so the full embedding shape stays visible with the category’s hotspots picked out in color.

Unlike scanpy.tl.embedding_density() (which evaluates scipy.stats.gaussian_kde pairwise – O(n^2) in cell count, and impractically slow for atlas-scale groups), this bins cells onto a fixed grid and smooths with a Gaussian filter – O(n + grid_size^2), so runtime stays flat as cell counts grow. Densities are also written to adata.obs[key_added] (scaled 0-1 within each group, evaluated at each cell’s own position), mirroring scanpy’s output so downstream code can rely on either.

Parameters:
  • adata – Annotated data with a computed embedding (adata.obsm['X_<basis>']).

  • groupby (str | None) – adata.obs column to compute one density panel per category. Omit for a single overall density panel.

  • groups (Sequence[str] | None) – Subset/order of categories to plot when groupby is given. Defaults to all categories.

  • figure_name (str | None) – Used as the figure’s suptitle. Defaults to a description of basis (and groupby, if given).

  • grid_size (int) – Resolution of the density grid per axis. Higher is smoother but slower; 200 is a good default even for very large atlases.

  • bw_scale (float) – Multiplier on the Scott’s-rule bandwidth; increase to smooth the density surface further, decrease to sharpen it.

  • density_threshold (float) – Scaled density (0-1) below which a cell is drawn flat grey instead of colored.

  • point_size (float | None) – Marker area per cell. Defaults to scanpy’s own 120000 / n_obs heuristic so it scales sensibly with atlas size.

  • grey_color (str | None) – Fill color for cells below density_threshold. Defaults to the config’s general.fallback_color.

  • grey_alpha (float) – Opacity of the below-threshold background cells, so the colored density signal on top stays the visual focus.

  • key_added (str | None) – adata.obs column the per-cell scaled density is written to. Defaults to f"{basis}_density" or f"{basis}_density_{groupby}".

  • config (PlotConfig | None) – Active PlotConfig. Uses defaults if omitted.

  • output_dir (str | Path) – Directory figures are written under.

  • show (bool) – Display the figure inline (e.g. in a Jupyter notebook) as it’s drawn.

  • basis (str)

  • cmap (str)

  • ncols (int)

  • panel_size (tuple)

  • save_name (str)

scplotkit.embeddings.gene_coexpression_umap(adata, gene1, gene2, color1='#e6299e', color2='#3cb428', mask_column=None, mask_values=None, figure_name=None, use_raw=True, layer=None, vmax_percentile=99.0, threshold=0.05, grey_color=None, point_size=None, add_outline=True, outline_width=(0.1, 0.05), outline_color=('black', 'white'), show_legend=True, config=None, output_dir='figures', basis='umap', show=False)[source]#

Bivariate color-blend UMAP showing where two markers co-occur.

Each gene is normalized to [0, 1] (clipped at vmax_percentile to avoid a few outlier cells compressing the rest of the scale), then blended additively into a single RGB color per cell – with the default magenta/green colors, gene1-only cells read magenta, gene2-only cells read green, and co-expressing cells read near-white. Magenta/green is used instead of the traditional red/green overlay because red-green color blindness (the most common form) makes that pairing indistinguishable; magenta’s blue component keeps it readable. Cells below threshold in both genes are drawn flat grey, matching the below-threshold convention used elsewhere in this module (see embedding_density()) rather than showing dozens of near-black dots.

This is a purely descriptive visualization – no statistical test for co-expression is performed; threshold only controls what counts as “on” for coloring purposes.

Parameters:
  • adata – Annotated data with a computed embedding (adata.obsm['X_<basis>']).

  • gene1 (str) – Genes to blend, looked up in layer, adata.raw (if use_raw), or adata.X, in that order of precedence.

  • gene2 (str) – Genes to blend, looked up in layer, adata.raw (if use_raw), or adata.X, in that order of precedence.

  • color1 (str) – Colors assigned to gene1-only and gene2-only cells. Colors combine additively, so the default magenta/green produce a near-white overlap; pick two colors with non-overlapping channels (e.g. a pure magenta and a pure green) for the cleanest three-way read, and avoid red/green – the two are indistinguishable under red-green color blindness.

  • color2 (str) – Colors assigned to gene1-only and gene2-only cells. Colors combine additively, so the default magenta/green produce a near-white overlap; pick two colors with non-overlapping channels (e.g. a pure magenta and a pure green) for the cleanest three-way read, and avoid red/green – the two are indistinguishable under red-green color blindness.

  • mask_column (str | None) – Restrict colored (non-grey) cells to those where mask_column is in mask_values. Both must be given to enable masking.

  • mask_values (Sequence | None) – Restrict colored (non-grey) cells to those where mask_column is in mask_values. Both must be given to enable masking.

  • figure_name (str | None) – Used as both plot title and output subdirectory name. Defaults to "{gene1}_{gene2}_coexpression".

  • vmax_percentile (float) – Upper percentile (over cells with nonzero expression) each gene is clipped to before normalizing to [0, 1].

  • threshold (float) – Normalized expression (0-1, per gene) below which a cell counts as “off” for that gene. Cells “off” for both genes are drawn grey.

  • grey_color (str | None) – Fill color for cells below threshold in both genes. Defaults to the config’s general.fallback_color.

  • point_size (float | None) – Marker area per cell. Defaults to scanpy’s own 120000 / n_obs heuristic so it scales sensibly with atlas size.

  • add_outline (bool) – Draw each point with a thin ring (as sc.pl.embedding’s own add_outline does) so cells stand out from the background and from each other. On by default since the additive color blend otherwise makes dense, similarly-colored regions hard to resolve into individual cells.

  • outline_width (tuple[float, float]) – Same meaning as the identically-named sc.pl.embedding params: outline_width is (outline_size, gap_size) as a fraction of the point radius, outline_color is (outline_color, gap_color).

  • outline_color (tuple[str, str]) – Same meaning as the identically-named sc.pl.embedding params: outline_width is (outline_size, gap_size) as a fraction of the point radius, outline_color is (outline_color, gap_color).

  • show_legend (bool) – Draw a small bivariate color-key inset showing how the blend maps to each gene’s expression level.

  • config (PlotConfig | None) – Active PlotConfig. Uses defaults if omitted.

  • output_dir (str | Path) – Directory figures are written under.

  • show (bool) – Display the figure inline (e.g. in a Jupyter notebook) as it’s drawn.

  • use_raw (bool)

  • layer (str | None)

  • basis (str)

scplotkit.embeddings.gene_expression_umap(adata, gene, mask_column=None, mask_values=None, figure_name=None, use_raw=True, layer=None, cmap='magma', vmin=0, vmax=None, config=None, output_dir='figures', basis='umap', show=False, **kwargs)[source]#

Plot a gene’s expression on an embedding, optionally masked to a subset of cells.

Cells outside mask_values (if given) are greyed out rather than dropped, so the full embedding shape is preserved. Saves two variants of the plot: without and with a colorbar.

Parameters:
  • adata – Annotated data with a computed embedding (adata.obsm['X_<basis>']).

  • gene (str) – Gene to plot, looked up in layer, adata.raw (if use_raw), or adata.X, in that order of precedence.

  • mask_column (str | None) – Restrict colored (non-grey) cells to those where mask_column is in mask_values. Both must be given to enable masking.

  • mask_values (Sequence | None) – Restrict colored (non-grey) cells to those where mask_column is in mask_values. Both must be given to enable masking.

  • figure_name (str | None) – Used as both plot title and output subdirectory name. Defaults to gene.

  • config (PlotConfig | None) – Active PlotConfig. Uses defaults if omitted.

  • output_dir (str | Path) – Directory figures are written under.

  • show (bool) – Display each figure inline (e.g. in a Jupyter notebook) as it’s drawn.

  • **kwargs – Forwarded to both sc.pl.embedding calls, overriding this function’s own defaults – anything the underlying scanpy function accepts.

  • use_raw (bool)

  • layer (str | None)

  • cmap (str)

  • vmin (float | None)

  • vmax (float | None)

  • basis (str)

scplotkit.embeddings.masked_umap(adata, color_by, figure_name, mask_column=None, mask_values=None, palette=None, config=None, output_dir='figures', basis='umap', show=False, **kwargs)[source]#

Plot a UMAP colored by color_by, restricted to mask_values.

Cells outside mask_values are greyed out. Saves three variants: no legend, with legend, and a version subset to only the masked cells.

Parameters:
  • adata – Annotated data with a computed embedding (adata.obsm['X_<basis>']).

  • color_by (str) – adata.obs column to color cells by.

  • figure_name (str) – Used as both plot title and output subdirectory name.

  • mask_column (str | None) – Column whose unique values become mask_values if not given explicitly. Only used as a default source for mask_values.

  • mask_values (Sequence | None) – Categories of color_by to keep visible. Defaults to all unique values of mask_column (or of color_by if neither is set).

  • palette (dict | None) – Optional {category: color} mapping. Falls back to the config’s registered palette for color_by, then to an auto-generated one.

  • config (PlotConfig | None) – Active PlotConfig. Uses defaults if omitted.

  • output_dir (str | Path) – Directory figures are written under.

  • show (bool) – Display each figure inline (e.g. in a Jupyter notebook) as it’s drawn. Scanpy closes the figure right after saving it, so without this the plots are written to disk but never rendered in the cell.

  • **kwargs – Forwarded to every sc.pl.embedding call, overriding this function’s own defaults (e.g. na_color, frameon, size) – anything the underlying scanpy function accepts.

  • basis (str)

scplotkit.embeddings.masked_umap_highlight(adata, color_by, figure_name, mask_column=None, mask_values=None, highlight_size=1.5, background_size=0.25, ordered=True, palette=None, config=None, output_dir='figures', basis='umap', show=False, **kwargs)[source]#

Like masked_umap(), but draws the masked population enlarged on top of a small greyed-out background rather than hiding the rest entirely.

show displays each figure inline (e.g. in a Jupyter notebook) as it’s drawn – scanpy closes the figure right after saving it, so without this the plots are written to disk but never rendered in the cell.

**kwargs are forwarded to every sc.pl.embedding call, overriding this function’s own defaults – anything the underlying scanpy function accepts.

Parameters:
  • color_by (str)

  • figure_name (str)

  • mask_column (str | None)

  • mask_values (Sequence | None)

  • highlight_size (float)

  • background_size (float)

  • ordered (bool)

  • palette (dict | None)

  • config (PlotConfig | None)

  • output_dir (str | Path)

  • basis (str)

  • show (bool)

scplotkit.composition#

Cell-type composition plots: stacked bars and clustered heatmaps.

All functions here work from a sample-by-cell-type proportion table (pd.crosstab under the hood), then offer several sample orderings: as-is, hierarchically clustered, or clustered within groups of a metadata column.

scplotkit.composition.abundance_bubble_grid(adata, level_column, sample_column='Sample_ID', subset_level=None, subset_value=None, dot_color='#37474f', min_size=20.0, max_size=500.0, figsize=None, title=None, xlabel=None, save_name='abundance_bubble_grid', config=None, output_dir='figures')[source]#

Dot grid of cell counts per (cell type, sample/dataset) pair.

Rows are level_column categories, columns are sample_column values (any per-sample or per-dataset column works); dot area encodes cell count. A single neutral dot_color is used throughout rather than a per-category palette, so size alone carries the value. Pairs with zero cells are drawn as a faint open ring rather than left blank, so gaps in atlas coverage/balance across studies are visible rather than ambiguous with “not shown”. Rows and columns are both ordered by descending total count, so the best-covered cell types and samples/datasets end up in the top-left.

Purely descriptive – raw cell counts only, no proportions and no statistical framing.

Parameters:
  • adata – Annotated data.

  • level_column (str) – adata.obs column defining the rows (e.g. cell type).

  • sample_column (str | None) – adata.obs column defining the columns (sample or dataset ID). Defaults to the first object/category column if not found.

  • subset_level (str | None) – Optionally restrict to cells where subset_level is in subset_value before counting (e.g. one lineage).

  • subset_value (str | Sequence | None) – Optionally restrict to cells where subset_level is in subset_value before counting (e.g. one lineage).

  • dot_color (str) – Fill color used for every filled dot.

  • min_size (float) – Marker area (in points^2) for the smallest nonzero and the largest count, respectively.

  • max_size (float) – Marker area (in points^2) for the smallest nonzero and the largest count, respectively.

  • save_name (str) – Filename (without extension) to save under. Pass None to skip saving.

  • config (PlotConfig | None) – Active PlotConfig. Uses defaults if omitted.

  • output_dir (str | Path | None) – Directory figures are written under.

  • figsize (tuple | None)

  • title (str | None)

  • xlabel (str | None)

scplotkit.composition.cluster_grouped_samples(ct_props, adata, sample_column, order_by_column, ascending=True)[source]#

Order samples by clustering within each group of order_by_column.

Groups themselves are ordered by their first observed value, ascending or descending as requested; samples within a group are hierarchically clustered (or left as-is if the group has a single sample).

Return type:

list

Parameters:
  • ct_props (DataFrame)

  • sample_column (str)

  • order_by_column (str)

  • ascending (bool)

scplotkit.composition.cluster_samples(ct_props)[source]#

Order samples by hierarchical (Ward) clustering of their proportions.

Return type:

Index

Parameters:

ct_props (DataFrame)

scplotkit.composition.composition_heatmap(adata, level_column, sample_column='Sample_ID', subset_level=None, subset_value=None, order_by_column=None, order_palette=None, figsize=(16, 6), title=None, cmap=None, save_name=None, config=None, output_dir='figures', **heatmap_kwargs)[source]#

Clustered heatmap of cell-type proportion per sample.

Parameters:
  • level_column (str)

  • sample_column (str | None)

  • subset_level (str | None)

  • subset_value (str | Sequence | None)

  • order_by_column (str | None)

  • order_palette (dict | None)

  • figsize (tuple)

  • title (str | None)

  • cmap (str | None)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.composition.stacked_barplots(adata, level_column, sample_column='Sample_ID', subset_level=None, subset_value=None, order_by_column=None, order_ascending=True, figsize=(16, 8), palette=None, order_palette=None, strip_prefix=None, save_name_prefix='composition', config=None, output_dir='figures')[source]#

Stacked bar plots of cell-type proportion per sample.

Returns a dict with up to three variants – "basic", "clustered" (samples ordered by hierarchical clustering), and "clustered_grouped" (present only if order_by_column is given: samples clustered within each group of that column).

Return type:

dict

Parameters:
  • level_column (str)

  • sample_column (str | None)

  • subset_level (str | None)

  • subset_value (str | Sequence | None)

  • order_by_column (str | None)

  • order_ascending (bool)

  • figsize (tuple)

  • palette (dict | None)

  • order_palette (dict | None)

  • strip_prefix (str | None)

  • save_name_prefix (str)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.composition.stacked_barplots_multi_meta(adata, level_column, sample_column='Sample_ID', metadata_columns=None, subset_level=None, subset_value=None, order_by_column=None, order_ascending=True, figsize=(16, 8), palette=None, meta_palettes=None, xlabel=None, strip_prefix=None, save_name_prefix='composition_multi_meta', config=None, output_dir='figures')[source]#

Like stacked_barplots(), with extra color-coded metadata strips drawn below the bars (e.g. treatment, timepoint, batch).

Return type:

dict

Parameters:
  • level_column (str)

  • sample_column (str | None)

  • metadata_columns (Sequence[str] | None)

  • subset_level (str | None)

  • subset_value (str | Sequence | None)

  • order_by_column (str | None)

  • order_ascending (bool)

  • figsize (tuple)

  • palette (dict | None)

  • meta_palettes (dict[str, dict] | None)

  • xlabel (str | None)

  • strip_prefix (str | None)

  • save_name_prefix (str)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.overview#

Dataset overview plots: sample/cell counts, abundance, and comparisons.

scplotkit.overview.cell_abundance_barplot(adata, cell_type_column, figsize=(8, 5), title_suffix=None, save_name=None, color='grey', xlabel=None, config=None, output_dir='figures')[source]#

Absolute and relative cell-count bar plots for one column.

Returns (fig_counts, fig_relative).

Parameters:
  • cell_type_column (str)

  • figsize (tuple)

  • title_suffix (str | None)

  • save_name (str | None)

  • color (str)

  • xlabel (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.overview.cells_per_patient_boxplot(adata, level_column, sample_column='Sample_ID', figsize=(10, 6), title=None, save_name=None, palette=None, xlabel=None, config=None, output_dir='figures')[source]#

Boxplot of cells-per-patient distribution, grouped by level_column.

Returns (fig, fig_grey) – a colored version and a grayscale twin.

Parameters:
  • level_column (str)

  • sample_column (str)

  • figsize (tuple)

  • title (str | None)

  • save_name (str | None)

  • palette (dict | None)

  • xlabel (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.overview.compare_cell_abundance_barplot(adata1, adata2, cell_type_column, label1='Dataset 1', label2='Dataset 2', color1='lightgray', color2='dimgray', figsize=(12, 6), title_suffix=None, save_name=None, xlabel=None, config=None, output_dir='figures')[source]#

Grouped bar plots comparing cell-type abundance between two datasets.

Returns (fig_counts, fig_relative).

Parameters:
  • cell_type_column (str)

  • label1 (str)

  • label2 (str)

  • color1 (str)

  • color2 (str)

  • figsize (tuple)

  • title_suffix (str | None)

  • save_name (str | None)

  • xlabel (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.overview.compare_cell_abundance_boxplot(adata1, adata2, cell_type_column, sample_column='Sample_ID', label1='Dataset 1', label2='Dataset 2', colored=False, color1=None, color2=None, figsize=(12, 5), title=None, save_name=None, high_dif=0, marker_column=None, groups_of_interest=None, config=None, output_dir='figures')[source]#

Paired per-sample boxplots comparing relative cell-type abundance between two datasets.

For each cell type, computes per-sample relative abundance (%) in each dataset and draws paired boxplots with individual sample dots overlaid – unlike compare_cell_abundance_barplot(), this shows the full per-sample distribution rather than just a single dataset-wide bar.

Parameters:
  • adata1 – Datasets to compare.

  • adata2 – Datasets to compare.

  • cell_type_column (str) – Columns in both datasets’ .obs.

  • sample_column (str) – Columns in both datasets’ .obs.

  • colored (bool) – Use two distinct auto-generated colors for label1/label2 instead of the default grayscale ("lightgray"/"dimgray"). Ignored if color1/color2 are given explicitly.

  • high_dif (int) – If > 0, show only the top N cell types by absolute difference in mean relative abundance. 0 shows all.

  • marker_column (str | None) – Optional .obs column (present in both datasets) whose unique values map to different point marker shapes.

  • groups_of_interest (Sequence | None) – If given, restrict (and order) the plot to these cell types instead of using high_dif.

  • label1 (str)

  • label2 (str)

  • color1 (str | None)

  • color2 (str | None)

  • figsize (tuple)

  • title (str | None)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.overview.sample_and_cell_counts_barplot(adata, level_column, sample_column='Sample_ID', figsize=(10, 5), title=None, save_name=None, palette=None, xlabel=None, config=None, output_dir='figures')[source]#

Side-by-side bars of samples-per-category and cells-per-category.

Returns (fig, fig_grey): a colored version and a grayscale twin (handy for figures that need to stay monochrome for print).

Parameters:
  • level_column (str)

  • sample_column (str)

  • figsize (tuple)

  • title (str | None)

  • save_name (str | None)

  • palette (dict | None)

  • xlabel (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.overview.sample_and_cell_counts_barplot_break_axis(adata, level_column, sample_column='Sample_ID', figsize=(5, 5), title=None, save_name=None, palette=None, xlabel=None, break_point=None, break_ratio=0.3, break_gap=0.02, plot_type='samples', config=None, output_dir='figures')[source]#

Like sample_and_cell_counts_barplot(), with a broken y-axis so a few outlier categories don’t compress the rest of the bars.

plot_type selects between "samples" (unique sample count per category) and "cells" (total cell count per category).

Parameters:
  • level_column (str)

  • sample_column (str)

  • figsize (tuple)

  • title (str | None)

  • save_name (str | None)

  • palette (dict | None)

  • xlabel (str | None)

  • break_point (float | None)

  • break_ratio (float)

  • break_gap (float)

  • plot_type (str)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.markers#

Marker gene visualizations: rank_genes_groups dot/matrix plots and matrix/violin plots for a user-supplied marker set.

scplotkit.markers.annotation_marker_matrixplot(adata, markers, groupby_column, layer=None, standard_scale='var', cmap='coolwarm', figsize=(12, 8), save_name=None, config=None, output_dir='figures', **kwargs)[source]#

Matrixplot of a user-supplied {cell_type: [marker_genes]} set, restricted to cells whose groupby_column value is one of markers’ keys.

**kwargs are forwarded to sc.pl.matrixplot, overriding this function’s own defaults – anything the underlying scanpy function accepts.

Parameters:
  • markers (dict[str, list[str]])

  • groupby_column (str)

  • layer (str | None)

  • standard_scale (str | None)

  • cmap (str)

  • figsize (tuple)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.markers.annotation_marker_stacked_violin(adata, markers, groupby_column, layer=None, standard_scale='var', cmap='coolwarm', figsize=(12, 8), save_name=None, config=None, output_dir='figures', **kwargs)[source]#

Stacked violin plot of a user-supplied {cell_type: [marker_genes]} set, restricted to cells whose groupby_column value is one of markers’ keys.

**kwargs are forwarded to sc.pl.stacked_violin, overriding this function’s own defaults – anything the underlying scanpy function accepts.

Parameters:
  • markers (dict[str, list[str]])

  • groupby_column (str)

  • layer (str | None)

  • standard_scale (str | None)

  • cmap (str)

  • figsize (tuple)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.markers.rank_genes_matrix_and_dot(adata, groupby_column, n_markers=5, method='wilcoxon', layer=None, standard_scale='var', use_expression=False, figsize=(12, 8), save_name=None, config=None, output_dir='figures', **kwargs)[source]#

Compute marker genes with sc.tl.rank_genes_groups and plot them as a dotplot and a matrixplot, both ordered by a dendrogram over groupby_column.

By default, dot/matrix color encodes log fold change (config.rank_genes defaults: values_to_plot="logfoldchanges", diverging cmap/vmin/ vmax). Set use_expression=True to instead color by mean expression, scaled per gene via standard_scale ("var" by default).

**kwargs are forwarded to both the sc.pl.rank_genes_groups_dotplot and sc.pl.rank_genes_groups_matrixplot calls, overriding this function’s own defaults – anything the underlying scanpy functions accept.

Returns (fig_dot, fig_matrix).

Parameters:
  • groupby_column (str)

  • n_markers (int)

  • method (str)

  • layer (str | None)

  • standard_scale (str | None)

  • use_expression (bool)

  • figsize (tuple)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.pseudobulk#

Pseudobulk plots: per-sample aggregated gene expression across groups or genes.

Each sample’s expression of a gene is first collapsed to a single mean value (the “pseudobulk”), then compared across groups with boxplots and individual sample points overlaid – the standard way to avoid pseudo-replication when comparing conditions across samples with many cells each.

scplotkit.pseudobulk.pseudobulk_boxplot(adata, gene, layer, sample_column='Sample_ID', group_by=None, celltype_column=None, celltype_of_interest=None, palette=None, marker_column=None, figsize=(4, 5), title=None, save_name=None, config=None, output_dir='figures')[source]#

Boxplot of per-sample pseudobulk (mean) expression of one gene.

Computes each sample’s mean gene expression from layer, then draws one box per group_by value (or a single box if omitted) with individual sample points jittered on top. Point shape can additionally be mapped to another column via marker_column.

Parameters:
  • gene (str)

  • layer (str)

  • sample_column (str)

  • group_by (str | None)

  • celltype_column (str | None)

  • celltype_of_interest (str | Sequence | None)

  • palette (dict | None)

  • marker_column (str | None)

  • figsize (tuple)

  • title (str | None)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.pseudobulk.pseudobulk_multigene_boxplot(adata, genes, layer, color_column, sample_column='Sample_ID', marker_column=None, celltype_column=None, celltype_of_interest=None, palette=None, groups_order=None, min_max_scale=True, figsize=(12, 5), title=None, save_name=None, config=None, output_dir='figures')[source]#

Pseudobulk expression boxplot for multiple genes, optionally min-max scaled per gene.

For each gene, computes per-sample mean expression, scaled to [0, 1] by default (set min_max_scale=False to plot raw mean expression instead). Draws one boxplot per color_column group per gene (side by side), with individual sample points overlaid; point shape can be mapped to marker_column.

If save_name is given, also exports {save_name}_raw.csv (unscaled per-sample mean expression per gene) and, when min_max_scale is True, {save_name}_minmax_scaled.csv (the scaled values used for the plot), both wide-format with one row per sample.

Parameters:
  • genes (Sequence[str])

  • layer (str)

  • color_column (str)

  • sample_column (str)

  • marker_column (str | None)

  • celltype_column (str | None)

  • celltype_of_interest (str | Sequence | None)

  • palette (dict | None)

  • groups_order (Sequence | None)

  • min_max_scale (bool)

  • figsize (tuple)

  • title (str | None)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.ridgeline#

Ridgeline (joy) plots: stacked, overlapping KDEs of a continuous value across groups.

scplotkit.ridgeline.ridgeline_plot(adata, obs_key, group_by, condition_column=None, celltype_column=None, celltype_of_interest=None, scale=False, palette=None, bw_adjust=1.0, overlap=0.6, figsize=None, alpha=0.72, show_median=True, title=None, save_name=None, config=None, output_dir='figures')[source]#

Ridgeline plot of a continuous .obs column, one ridge per group_by value.

Parameters:
  • obs_key (str) – Continuous .obs column to plot (x-axis).

  • group_by (str) – Categorical .obs column defining the rows (one ridge per value).

  • condition_column (str | None) – If given, overlays one KDE per condition value on each ridge, colored by condition (looked up via palette/config instead of group_by).

  • celltype_column (str | None) – Optional subsetting before computing distributions.

  • celltype_of_interest (str | Sequence | None) – Optional subsetting before computing distributions.

  • scale (bool) – Z-score obs_key across all cells before plotting.

  • bw_adjust (float) – Bandwidth multiplier for the KDE (like R’s adjust=).

  • overlap (float) – Fraction of row height that ridges overlap (0 = no overlap).

  • show_median (bool) – Draw a vertical tick at the median of each distribution.

  • palette (dict | None)

  • figsize (tuple | None)

  • alpha (float)

  • title (str | None)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.enrichment#

Over-representation analysis (ORA) dot plots, e.g. from Enrichr/gseapy results.

scplotkit.enrichment.ora_dotplot(csv_path, n_top=20, gene_set_filter=None, padj_threshold=0.05, x_metric='gene_ratio', cmap='magma', figsize=None, title=None, save_name=None, config=None, output_dir='figures')[source]#

Dot plot overview of Over-Representation Analysis (ORA) results.

Expects a CSV (e.g. exported from Enrichr/gseapy) with columns Gene_set, Term, Overlap ("n/total" strings), Adjusted P-value, Odds Ratio, Combined Score. Dot size scales with the number of overlapping genes; dot color encodes -log10(adjusted p-value).

Parameters:
  • n_top (int) – Number of top terms to display, ranked by Combined Score.

  • gene_set_filter (str | list[str] | None) – Restrict to specific Gene_set value(s).

  • padj_threshold (float) – Only show terms with adjusted p-value below this cutoff.

  • x_metric (str) – 'gene_ratio', 'odds_ratio', or 'combined_score'.

  • csv_path (str | Path)

  • cmap (str)

  • figsize (tuple | None)

  • title (str | None)

  • save_name (str | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.sankey#

Sankey diagrams, sunbursts and treemaps showing how cells flow through / nest within a hierarchy of annotation levels (e.g. Level_1 -> Level_4).

scplotkit.sankey.hierarchical_counts(adata, levels)[source]#

Return indented "label [count]" lines describing cell counts nested across 1-3 annotation levels (coarse to fine).

Return type:

list[str]

Parameters:

levels (list[str])

scplotkit.sankey.hierarchical_counts_string(adata, levels)[source]#

Newline-joined version of hierarchical_counts().

Return type:

str

Parameters:

levels (list[str])

scplotkit.sankey.sankey_plot(adata, levels, save_name=None, width=1100, height=800, show_labels=True, node_color='grey', link_color='lightgrey', config=None, output_dir='figures')[source]#

Sankey diagram of cell flow across 1-3 nested annotation levels.

Requires the optional sankey extra (pip install scplotkit[sankey]) for plotly/kaleido.

Parameters:
  • levels (list[str])

  • save_name (str | None)

  • width (int)

  • height (int)

  • show_labels (bool)

  • node_color (str)

  • link_color (str)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.sankey.sunburst_plot(adata, levels, title=None, save_name=None, width=900, height=900, palette=None, config=None, output_dir='figures')[source]#

Sunburst of a nested cell-type taxonomy (e.g. ["Level_1", ..., "Level_4"]), an alternative to sankey_plot() for seeing the whole tree at a glance.

Ring 1 (innermost) is colored by levels[0] using the config’s registered palette for that column (falling back to an auto-generated one); deeper rings reuse their top-level ancestor’s color, progressively lightened by depth. Purely descriptive – segment size is raw cell count, no statistical framing.

Requires the optional sankey extra (pip install scplotkit[sankey]) for plotly/kaleido.

Parameters:
  • levels (list[str])

  • title (str | None)

  • save_name (str | None)

  • width (int)

  • height (int)

  • palette (dict | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)

scplotkit.sankey.treemap_plot(adata, levels, title=None, save_name=None, width=1100, height=700, palette=None, config=None, output_dir='figures')[source]#

Treemap of a nested cell-type taxonomy (e.g. ["Level_1", ..., "Level_4"]), an alternative to sankey_plot() – rectangle area makes relative size easier to compare at a glance than a sunburst’s arc angles, especially with many leaf categories.

Coloring follows the same rule as sunburst_plot(): top-level branches take the config’s palette for levels[0], descendants reuse their ancestor’s color lightened by depth. Purely descriptive – tile area is raw cell count, no statistical framing.

Requires the optional sankey extra (pip install scplotkit[sankey]) for plotly/kaleido.

Parameters:
  • levels (list[str])

  • title (str | None)

  • save_name (str | None)

  • width (int)

  • height (int)

  • palette (dict | None)

  • config (PlotConfig | None)

  • output_dir (str | Path | None)