scPyviewer API Tutorial#

scPyviewer is a Python-native viewer and programmatic API for single-cell AnnData (.h5ad) objects.
This notebook walks through every API function with runnable examples.

Installation#

pip install scPyviewer          # core (no Streamlit)
pip install 'scPyviewer[all]'   # core + viewer + clustering + xlsx export

Contents#

  1. Setup & toy dataset

  2. Load a dataset

  3. Global style

  4. plot_embedding — UMAP / t-SNE scatter

  5. plot_multigene — multi-gene expression grid

  6. plot_violin — violin / box plot

  7. plot_dotplot — dot plot

  8. plot_composition — stacked bar

  9. Table functions

  10. Export figures & tables

  11. Publication-quality workflow

  12. plot_heatmap — gene × group heatmap

  13. plot_matrixplot — mean expression matrix

  14. plot_stacked_violin — multi-gene violin stack

  15. plot_tracksplot — single-cell expression tracks

  16. plot_correlation — inter-group correlation heatmap

  17. plot_bar — grouped comparison bars (± error)

  18. plot_trend — expression trend over an ordered variable

  19. plot_radar — multi-gene signature radar

  20. plot_embedding_3d — 3-D embedding scatter


1 · Setup & toy dataset #

We build a small synthetic AnnData so the notebook runs without downloading data.
Replace tmp_path with your own *.prepared.h5ad when working with real data.

import warnings
warnings.filterwarnings("ignore")

import numpy as np
import pandas as pd
import anndata as ad
import scipy.sparse as sp
import tempfile, os
import matplotlib.pyplot as plt

# ── build a synthetic 200-cell x 80-gene AnnData with light structure ─────
rng = np.random.default_rng(42)
n_cells, n_genes = 200, 80
gene_names = [f"Gene{i:03d}" for i in range(n_genes)]

cell_types = np.array(["T cell"] * 60 + ["B cell"] * 50
                      + ["NK cell"] * 40 + ["Monocyte"] * 50)
ct_levels = ["T cell", "B cell", "NK cell", "Monocyte"]
batch = rng.choice(["Sample_A", "Sample_B"], n_cells)

# ordered timepoint axis (for plot_trend) + numeric day
timepoint = rng.choice(["D0", "D3", "D7", "D14"], n_cells)
day_num = np.array([{"D0": 0, "D3": 3, "D7": 7, "D14": 14}[t] for t in timepoint], float)

counts = (
    sp.random(n_cells, n_genes, density=0.35, format="csr", random_state=42)
    .toarray() * 12
).astype(np.float32)
# each cell type over-expresses its own 10-gene marker block
for k, ct in enumerate(ct_levels):
    idx = np.where(cell_types == ct)[0]
    counts[np.ix_(idx, np.arange(k * 10, k * 10 + 10))] += rng.uniform(15, 30, (len(idx), 10))
# Gene000 rises over the timepoint axis (for a visible trend)
counts[:, 0] += day_num * 1.4

lognorm = np.log1p(
    counts / np.clip(counts.sum(axis=1, keepdims=True), 1, None) * 1e4
).astype(np.float32)

obs = pd.DataFrame({
    "cell_type": pd.Categorical(cell_types, categories=ct_levels),
    "batch":     pd.Categorical(batch),
    "timepoint": pd.Categorical(timepoint, categories=["D0", "D3", "D7", "D14"], ordered=True),
    "n_counts":  counts.sum(axis=1),
})

adata = ad.AnnData(
    X=sp.csr_matrix(lognorm),
    obs=obs,
    var=pd.DataFrame(index=gene_names),
)
adata.layers["lognorm"] = sp.csr_matrix(lognorm)

# embeddings with per-cell-type separation: 2-D UMAP/t-SNE + a 3-D PCA
def _clustered(dim):
    centers = {ct: rng.normal(0, 6, dim) for ct in ct_levels}
    return (np.array([centers[ct] for ct in cell_types])
            + rng.normal(0, 1.0, (n_cells, dim))).astype(np.float32)

adata.obsm["X_umap"] = _clustered(2)
adata.obsm["X_tsne"] = _clustered(2)
adata.obsm["X_pca"]  = _clustered(3)   # 3-D -> used by plot_embedding_3d

# synthetic marker/DE table pointing at each type's marker block
rows = []
for g_idx, group in enumerate(ct_levels):
    for rank in range(1, 11):
        gene = gene_names[g_idx * 10 + (rank - 1)]
        rows.append(dict(group=group, rank=rank, gene=gene,
                         logfoldchange=float(rng.uniform(1.0, 3.0)),
                         score=float(rng.uniform(1, 10)),
                         pval=float(rng.uniform(0, 0.05)),
                         pval_adj=float(rng.uniform(0, 0.1))))
mdf = pd.DataFrame(rows)
adata.uns["scPyviewer_markers"] = {c: mdf[c].tolist() for c in mdf.columns}
adata.uns["scPyviewer"] = {
    "group_key": "cell_type",
    "embeddings": ["X_umap", "X_tsne", "X_pca"],
    "schema": {
        "categorical_obs": ["cell_type", "batch", "timepoint"],
        "numeric_obs": ["n_counts"],
    },
    "version": "0.5.0",
}

# save to a temp file (mimics a real .prepared.h5ad)
tmp_path = os.path.join(tempfile.mkdtemp(), "toy.prepared.h5ad")
adata.write_h5ad(tmp_path)
print("Toy dataset written to:", tmp_path)
Toy dataset written to: /tmp/tmpwxln15pd/toy.prepared.h5ad

2 · Load a dataset #

import scPyviewer as sv

print("scPyviewer version:", sv.__version__)

# load_dataset() reads a *.prepared.h5ad and returns a Dataset handle
ds = sv.load_dataset(tmp_path)
print(ds)
scPyviewer version: 0.5.0
Dataset(toy.prepared.h5ad: 200 cells x 80 genes, group_key='cell_type')
# inspect the dataset
print("Cells      :", ds.n_obs)
print("Genes      :", ds.n_vars)
print("Group key  :", ds.group_key)       # primary clustering column
print("Embeddings :", ds.embeddings)      # available 2-D projections
print("Categorical:", ds.categorical)     # obs columns available for grouping

# search for genes (substring match)
print("\nGenes matching '01':", ds.genes("01"))
Cells      : 200
Genes      : 80
Group key  : cell_type
Embeddings : ['X_umap', 'X_tsne', 'X_pca']
Categorical: ['cell_type', 'batch', 'timepoint']

Genes matching '01': ['Gene001', 'Gene010', 'Gene011', 'Gene012', 'Gene013', 'Gene014', 'Gene015', 'Gene016', 'Gene017', 'Gene018', 'Gene019']

3 · Global style #

sv.set_publication_style() (v0.4.1+) applies a publication-quality style in one call — Helvetica font stack, no top/right spines, frameless legends, editable SVG text, 300 dpi, and a colour-blind-safe Okabe-Ito colour cycle that every categorical plot_* adopts automatically. A second built-in palette, "publication", offers a muted print-friendly set.

For finer-grained, single-setting overrides, sv.set_style() is still available. Either way, individual plot_* functions can override any setting via their own parameters.

# set a clean, publication-quality global style for the whole notebook (v0.4.1+)
# ONE call sets: Helvetica font stack, no top/right spines, frameless legends,
# editable SVG text, and a colour-blind-safe Okabe-Ito palette that every
# categorical plot below picks up automatically.
sv.set_publication_style(palette="okabe-ito", base_fontsize=10, dpi=120)

# switch palettes any time:
#   sv.set_publication_style(palette="publication")   # muted in-house set
#   sv.get_palette("okabe-ito")                        # -> list of hex codes
# or use the lower-level knob for a single override:
#   sv.set_style(font_family="Arial", base_fontsize=10, dpi=120)
print("Publication style applied (Okabe-Ito, colour-blind safe).")
Publication style applied (Okabe-Ito, colour-blind safe).

4 · plot_embedding #

Scatter plot of any 2-D embedding (UMAP, t-SNE, PCA …), colored by a metadata column or gene expression.

# ── 4.1  default: color by cell type ─────────────────────────────────────
fig = sv.plot_embedding(ds, color="cell_type")
plt.show()
_images/1860366c99f64a11b1a6ef7396e163aca1019a6d229a57d9aacea94fb7b69605.png
# ── 4.2  color by gene expression ────────────────────────────────────────
fig = sv.plot_embedding(ds, gene="Gene000")
plt.show()
_images/875cec64f2b0f379c0ed17f666e02ca93130f1a12c19513501882483c284bdbb.png
# ── 4.3  t-SNE instead of UMAP ───────────────────────────────────────────
fig = sv.plot_embedding(ds, color="cell_type", embedding="X_tsne")
plt.show()
_images/1ae3a2188263205e72a30f56545027ca99236485ecea9b1061d4ad591b3a9444.png
# ── 4.4  full typography control ─────────────────────────────────────────
fig = sv.plot_embedding(
    ds,
    color="cell_type",
    # layout
    figsize=(7, 5.5),
    dpi=150,
    # scatter
    point_size=6,
    alpha=0.85,
    # labels
    title="Immune cell types — UMAP",
    title_fontsize=14,
    label_groups=True,
    label_fontsize=9,
    xlabel="UMAP 1",
    ylabel="UMAP 2",
    xlabel_fontsize=11,
    ylabel_fontsize=11,
    tick_fontsize=9,
    # legend (shown when label_groups=False)
    show_legend=False,
    legend_fontsize=9,
    # font
    font_family="DejaVu Sans",
)
plt.show()
_images/4f610096ed89d4bec90a1d7e1f468c3f45d3251904ce9fac5d12f24e7399facb.png
# ── 4.5  gene expression with colorbar customization ─────────────────────
fig = sv.plot_embedding(
    ds,
    gene="Gene010",
    figsize=(6, 5),
    dpi=150,
    cmap="magma",
    point_size=8,
    title="Gene010 expression",
    title_fontsize=13,
    colorbar_label="log-norm expr",
    colorbar_fontsize=10,
)
plt.show()
_images/f29d7ee581c8b4a74a3d0fdaa24461a4b65b57dfe2cadd5417c4dc2e2202fdf9.png

5 · plot_multigene #

Grid of embedding panels, one per gene.

# ── 5.1  default ─────────────────────────────────────────────────────────
top_genes = [f"Gene{i:03d}" for i in range(6)]
fig = sv.plot_multigene(ds, genes=top_genes)
plt.show()
_images/7eadb12c1f425b398ea7e89dec9a02e5acd7e0598795a9a5a837a2ff4892d5fb.png
# ── 5.2  2-column layout with custom typography ───────────────────────────
fig = sv.plot_multigene(
    ds,
    genes=top_genes,
    ncol=2,                      # 2-column grid
    figsize=(7, 10),             # override auto-size
    dpi=150,
    point_size=4,
    cmap="RdBu_r",
    suptitle="Top marker genes",
    suptitle_fontsize=14,
    panel_title_fontsize=11,
    colorbar_fontsize=8,
    font_family="DejaVu Sans",
)
plt.show()
_images/849b18401639dfb65a510c067be18d39a96c945aecd1ceca3cd719cbf90b3328.png

6 · plot_violin #

Violin or box plot of gene expression per group.

# ── 6.1  default violin ───────────────────────────────────────────────────
fig = sv.plot_violin(ds, gene="Gene000", group="cell_type")
plt.show()
_images/143f51f21c945cccb9c75199b150d4863abeb885f8d2b80b52e7f8c1e2ae4935.png
# ── 6.2  box plot with data points ────────────────────────────────────────
fig = sv.plot_violin(
    ds,
    gene="Gene000",
    group="cell_type",
    kind="box",
    show_points=True,
)
plt.show()
_images/98ad494969bab42329427287ab4505bcf2b7df7a7818df3c539dfab231eaf581.png
# ── 6.3  publication-quality typography ──────────────────────────────────
fig = sv.plot_violin(
    ds,
    gene="Gene000",
    group="cell_type",
    kind="violin",
    show_points=True,
    # layout
    figsize=(8, 4.5),
    dpi=150,
    # typography
    title="Gene000 expression by cell type",
    title_fontsize=14,
    xlabel="Cell type",
    ylabel="Log-normalized expression",
    xlabel_fontsize=12,
    ylabel_fontsize=12,
    tick_fontsize=10,
    rotation=20,
    font_family="DejaVu Sans",
)
plt.show()
_images/1a7625b12ff7a6a67abd2afe036c4425e60c680813fb5bbfe3fb703aa1e006e7.png
# ── 6.4  split by batch ───────────────────────────────────────────────────
fig = sv.plot_violin(ds, gene="Gene005", group="batch")
plt.show()
_images/73a96ac3c15a2da7e709edfd701a9764ce814682d2a63d7b53b432685a8710a5.png

7 · plot_dotplot #

Dot size = fraction of cells expressing the gene.
Dot color = mean log-normalized expression.

# ── 7.1  default ─────────────────────────────────────────────────────────
marker_genes = [f"Gene{i:03d}" for i in [0, 10, 20, 30, 40]]
fig = sv.plot_dotplot(ds, genes=marker_genes, group="cell_type")
plt.show()
_images/4021d00f78b58fee666c52aedcee05ccd8c54b56fc0d3be2ad2ebb16fbd5309f.png
# ── 7.2  scale within each gene (standard_scale="var") ───────────────────
fig = sv.plot_dotplot(
    ds,
    genes=marker_genes,
    group="cell_type",
    standard_scale="var",   # normalize 0-1 per gene column
    cmap="Blues",
)
plt.show()
_images/8638c2806673be3615e9e64e3c021b6a220d84008ef5970c76ebac210805466b.png
# ── 7.3  full typography control ─────────────────────────────────────────
fig = sv.plot_dotplot(
    ds,
    genes=marker_genes,
    group="cell_type",
    standard_scale="var",
    cmap="viridis",
    size_scale=250,
    # layout
    figsize=(7, 3.5),
    dpi=150,
    # typography
    title="Marker gene expression",
    title_fontsize=13,
    xlabel="Gene",
    ylabel="Cell type",
    xlabel_fontsize=11,
    ylabel_fontsize=11,
    tick_fontsize=9,
    gene_label_rotation=30,
    colorbar_label="Scaled mean expr",
    colorbar_fontsize=9,
    legend_fontsize=8,
    font_family="DejaVu Sans",
)
plt.show()
_images/d3d30c678961af93844043cd9807343545fec0f146f101a9e5d5fd7e7dddc56f.png

8 · plot_composition #

Stacked bar showing cell-type proportions across samples / conditions.

# ── 8.1  default (fraction) ───────────────────────────────────────────────
fig = sv.plot_composition(ds, group="cell_type", split="batch")
plt.show()
_images/7d16fb975d5018ded6cf0ea0b62ec70a399b6041f915720ebbc928c561e8a21e.png
# ── 8.2  raw cell counts ─────────────────────────────────────────────────
fig = sv.plot_composition(ds, group="cell_type", split="batch", normalize=False)
plt.show()
_images/3ec0c895752202c5011827b96c34d8350a367f30db37cc90fb6ec59e3b681fdb.png
# ── 8.3  full typography control ─────────────────────────────────────────
fig = sv.plot_composition(
    ds,
    group="cell_type",
    split="batch",
    normalize=True,
    sort_groups=True,
    # layout
    figsize=(6, 4),
    dpi=150,
    bar_width=0.65,
    # typography
    title="Cell-type composition per sample",
    title_fontsize=13,
    xlabel="Sample",
    ylabel="Fraction of cells",
    xlabel_fontsize=11,
    ylabel_fontsize=11,
    tick_fontsize=9,
    rotation=0,
    legend_fontsize=8,
    legend_title_fontsize=9,
    font_family="DejaVu Sans",
)
plt.show()
_images/cb8509a516d8ef14e8492c76a41dfcb46e93118dd348541c02ddbfcaa657db3b.png

9 · Table functions #

# ── 9.1  marker / DE table ───────────────────────────────────────────────
mk = sv.markers_table(ds, top_n=5)      # top 5 genes per group
print(f"Shape: {mk.shape}")
mk.head(10)
Shape: (20, 7)
gene group logfoldchange pval pval_adj rank score
0 Gene010 B cell 1.306201 0.033505 0.043904 1 3.981491
1 Gene011 B cell 2.468390 0.037919 0.099225 2 8.808381
2 Gene012 B cell 2.508722 0.041618 0.073027 3 8.669613
3 Gene013 B cell 2.603604 0.023760 0.063829 4 9.412149
4 Gene014 B cell 2.029879 0.021568 0.081973 5 8.659333
5 Gene030 Monocyte 2.855716 0.006394 0.034900 1 9.642034
6 Gene031 Monocyte 2.396289 0.016239 0.002329 2 2.994026
7 Gene032 Monocyte 1.307043 0.032655 0.064891 3 6.060965
8 Gene033 Monocyte 2.556721 0.013675 0.001558 4 4.737533
9 Gene034 Monocyte 1.413260 0.008910 0.002014 5 3.811490
# filter to a single cell type
t_markers = sv.markers_table(ds, group="T cell", top_n=5)
t_markers
gene group logfoldchange pval pval_adj rank score
0 Gene000 T cell 1.839621 0.006429 0.038000 1 2.900989
1 Gene001 T cell 2.151643 0.030541 0.029625 2 4.239394
2 Gene002 T cell 1.691701 0.043916 0.032203 3 8.116062
3 Gene003 T cell 2.143032 0.002667 0.073786 4 3.503461
4 Gene004 T cell 1.342007 0.024352 0.018447 5 4.831413
# sort by logfoldchange instead of rank
sv.markers_table(ds, sort_by="logfoldchange", ascending=False, top_n=5)
gene group logfoldchange pval pval_adj rank score
0 Gene013 B cell 2.603604 0.023760 0.063829 4 9.412149
1 Gene015 B cell 2.598709 0.012446 0.070962 6 9.656975
2 Gene016 B cell 2.513839 0.045345 0.057353 7 9.426506
3 Gene012 B cell 2.508722 0.041618 0.073027 3 8.669613
4 Gene011 B cell 2.468390 0.037919 0.099225 2 8.808381
5 Gene030 Monocyte 2.855716 0.006394 0.034900 1 9.642034
6 Gene036 Monocyte 2.596337 0.006878 0.056407 7 6.109805
7 Gene033 Monocyte 2.556721 0.013675 0.001558 4 4.737533
8 Gene031 Monocyte 2.396289 0.016239 0.002329 2 2.994026
9 Gene039 Monocyte 2.255504 0.001554 0.072293 10 5.845103
10 Gene029 NK cell 2.672232 0.011309 0.052481 10 9.396820
11 Gene027 NK cell 2.635632 0.024565 0.070446 8 8.131826
12 Gene025 NK cell 2.580060 0.016849 0.066205 6 5.612976
13 Gene022 NK cell 2.502624 0.017191 0.026165 3 5.181423
14 Gene020 NK cell 2.434039 0.043820 0.030957 1 3.251539
15 Gene001 T cell 2.151643 0.030541 0.029625 2 4.239394
16 Gene003 T cell 2.143032 0.002667 0.073786 4 3.503461
17 Gene007 T cell 2.085088 0.021179 0.029941 8 7.767555
18 Gene000 T cell 1.839621 0.006429 0.038000 1 2.900989
19 Gene006 T cell 1.762820 0.030014 0.009226 7 1.350197
# ── 9.2  composition table ────────────────────────────────────────────────
comp = sv.composition_table(ds, group="cell_type", split="batch")
comp   # fraction of each cell type per batch
cell_type batch B cell Monocyte NK cell T cell
0 Sample_A 0.242424 0.282828 0.20202 0.272727
1 Sample_B 0.257426 0.217822 0.19802 0.326733
# ── 9.3  metadata table ───────────────────────────────────────────────────
meta = sv.metadata_table(ds)
print(f"Shape: {meta.shape}")
meta.head()
Shape: (200, 4)
cell_type batch timepoint n_counts
0 T cell Sample_A D3 376.818970
1 T cell Sample_B D14 389.045715
2 T cell Sample_B D3 391.904602
3 T cell Sample_A D7 394.844543
4 T cell Sample_A D3 394.846191

10 · Export figures & tables #

# ── 10.1  export all standard figures ─────────────────────────────────────
fig_dir = "/tmp/scpyviewer_figs"

written = sv.export_figures(
    ds,
    outdir=fig_dir,
    formats=["png", "pdf"],      # any of: png, pdf, svg
    dpi=200,
    # apply consistent typography to all exported figures
    title_fontsize=12,
    tick_fontsize=9,
    label_fontsize=10,
    font_family="DejaVu Sans",
)

print("Written files:")
for p in written:
    print(" ", p)
Written files:
  /tmp/scpyviewer_figs/embedding_group.png
  /tmp/scpyviewer_figs/embedding_group.pdf
  /tmp/scpyviewer_figs/embedding_gene.png
  /tmp/scpyviewer_figs/embedding_gene.pdf
  /tmp/scpyviewer_figs/multigene_grid.png
  /tmp/scpyviewer_figs/multigene_grid.pdf
  /tmp/scpyviewer_figs/violin.png
  /tmp/scpyviewer_figs/violin.pdf
  /tmp/scpyviewer_figs/dotplot.png
  /tmp/scpyviewer_figs/dotplot.pdf
  /tmp/scpyviewer_figs/composition.png
  /tmp/scpyviewer_figs/composition.pdf
# ── 10.2  save a single figure manually ──────────────────────────────────
fig = sv.plot_embedding(ds, color="cell_type", dpi=200, figsize=(7, 5))
fig.savefig("/tmp/umap_celltypes.png", dpi=200, bbox_inches="tight")
fig.savefig("/tmp/umap_celltypes.pdf",           bbox_inches="tight")
fig.savefig("/tmp/umap_celltypes.svg",           bbox_inches="tight")
print("Saved PNG / PDF / SVG")
Saved PNG / PDF / SVG
_images/78e009cc603307f6711615120ee5b94735a2d55d4ad7b0ae7573c11d1640b6e4.png
# ── 10.3  export tables ───────────────────────────────────────────────────
tbl_dir = "/tmp/scpyviewer_tables"

written = sv.export_tables(
    ds,
    outdir=tbl_dir,
    formats=["csv", "tsv"],   # add "xlsx" if openpyxl is installed
    top_n=25,
)

print("Written tables:")
for p in written:
    print(" ", p)
Written tables:
  /tmp/scpyviewer_tables/markers.csv
  /tmp/scpyviewer_tables/markers.tsv
  /tmp/scpyviewer_tables/composition.csv
  /tmp/scpyviewer_tables/composition.tsv
  /tmp/scpyviewer_tables/metadata.csv
  /tmp/scpyviewer_tables/metadata.tsv

11 · Publication-quality workflow #

A complete example: global style → per-figure fine-tuning → batch export at 300 DPI.

# ── Step 1: apply a publication-quality global style for the whole analysis ─
sv.set_publication_style(
    palette="okabe-ito",   # colour-blind-safe; try palette="publication"
    base_fontsize=11,
    dpi=300,               # print resolution
)
# ── Step 2: UMAP overview for panel A ─────────────────────────────────────
fig_a = sv.plot_embedding(
    ds,
    color="cell_type",
    figsize=(5.5, 4.5),
    point_size=5, alpha=0.8,
    title="A  Cell-type annotation",
    title_fontsize=12,
    label_fontsize=8,
    xlabel_fontsize=10, ylabel_fontsize=10,
    tick_fontsize=8,
)
plt.show()
_images/51856ec57c03dd273122d9fe157f11112d5d2251eed7e088735eaeefb08b4813.png
# ── Step 3: dot plot for panel B ──────────────────────────────────────────
fig_b = sv.plot_dotplot(
    ds,
    genes=[f"Gene{i:03d}" for i in [0, 10, 20, 30, 40, 50]],
    group="cell_type",
    standard_scale="var",
    cmap="Blues",
    figsize=(7, 3),
    title="B  Marker gene expression",
    title_fontsize=12,
    tick_fontsize=9,
    colorbar_fontsize=9,
    legend_fontsize=8,
    gene_label_rotation=35,
)
plt.show()
_images/9413a3c674ccb3163ac4368fbc495d554ddf02dfef00d54e685eb512cca7a295.png
# ── Step 4: composition bar for panel C ───────────────────────────────────
fig_c = sv.plot_composition(
    ds,
    group="cell_type", split="batch",
    figsize=(4.5, 4),
    title="C  Sample composition",
    title_fontsize=12,
    xlabel_fontsize=10, ylabel_fontsize=10,
    tick_fontsize=9, rotation=0,
    legend_fontsize=8,
)
plt.show()
_images/d64141a6ddf6dd7604b04dbcd7d1149d871fad32c9c0b3423afba256e835e0a0.png
# ── Step 5: batch-export all panels at 300 DPI ────────────────────────────
out = "/tmp/paper_figs"
os.makedirs(out, exist_ok=True)

for name, fig in [("panelA_umap", fig_a),
                  ("panelB_dotplot", fig_b),
                  ("panelC_composition", fig_c)]:
    for fmt in ("png", "pdf", "svg"):
        path = os.path.join(out, f"{name}.{fmt}")
        fig.savefig(path, dpi=300, bbox_inches="tight")

print("Exported to", out)
print(os.listdir(out))
Exported to /tmp/paper_figs
['panelB_dotplot.pdf', 'panelC_composition.svg', 'panelB_dotplot.png', 'panelA_umap.png', 'panelC_composition.pdf', 'panelA_umap.svg', 'panelC_composition.png', 'panelA_umap.pdf', 'panelB_dotplot.svg']

Parameter quick-reference#

Parameter

Type

Applies to

What it controls

figsize

(float, float)

all

Figure width × height in inches

dpi

int

all

Resolution (dots per inch)

title

str

all

Figure title text

title_fontsize

float

all

Title font size

xlabel / ylabel

str

violin, dotplot, composition, heatmap, matrixplot, stacked_violin, tracksplot

Axis label text

xlabel_fontsize / ylabel_fontsize

float

violin, dotplot, composition, heatmap, matrixplot, stacked_violin, tracksplot

Axis label font size

tick_fontsize

float

all

Tick-label font size

legend_fontsize

float

embedding, dotplot, composition

Legend entry font size

colorbar_fontsize

float

embedding (gene), multigene, dotplot, heatmap, matrixplot, tracksplot, correlation

Colorbar text size

label_fontsize

float

embedding

Centroid text label size

panel_title_fontsize

float

multigene

Per-panel title size

suptitle_fontsize

float

multigene

Figure super-title size

gene_label_rotation

int

dotplot

X-axis gene label rotation (°)

gene_label_fontsize

float

stacked_violin

Gene label font size on Y axis

rotation

int

violin, composition

X-tick rotation (°)

font_family

str

all

Per-figure font family

point_size

float

embedding, multigene

Scatter point diameter

alpha

float

embedding, multigene

Point transparency

cmap

str

embedding, multigene, dotplot, heatmap, matrixplot, tracksplot, correlation

Matplotlib colormap

vmin / vmax

float

heatmap, matrixplot, tracksplot, correlation

Clip color range

standard_scale

str

dotplot, heatmap, matrixplot

None, "var", or "group"

swap_axes

bool

heatmap, matrixplot, stacked_violin

Transpose gene/group axes

show_group_bar

bool

heatmap

Show group color strip

annotate

bool

matrixplot, correlation

Overlay numeric values

annotation_fmt

str

matrixplot, correlation

Python format string, e.g. ".2f"

inner

str

stacked_violin

Violin inner: "box", "quartile", "point", None

linewidth

float

stacked_violin

Violin outline width

track_height

float

tracksplot

Height of each gene track (inches)

show_group_labels

bool

tracksplot

Label group boundaries

method

str

correlation

"pearson" or "spearman"

kind

str

violin

"violin" or "box"

show_points

bool

violin

Overlay jittered data points

normalize

bool

composition

Fraction vs. raw counts


Generated with scPyviewer v0.4.0. See github.com/xuan13hao/scPyviewer for the source.


12 · plot_heatmap #

A genes × groups heatmap showing mean log-normalized expression.
Better than Scanpy’s sc.pl.heatmap: full typography control, per-cell or per-group view, flexible axis orientation, and publication-ready colorbars.

heatmap_genes = [f"Gene{i:03d}" for i in [0, 5, 10, 15, 20, 25, 30]]

# ── 12.1  default: genes (rows) × cell types (columns) ────────────────────
fig = sv.plot_heatmap(ds, genes=heatmap_genes, group="cell_type")
plt.show()
_images/78ff2820993f76554b340c1d3f36dd2b99897cf49c4a0e928c7194c6347ab705.png
# ── 12.2  swap axes: cell types (rows) × genes (columns) ──────────────────
fig = sv.plot_heatmap(ds, genes=heatmap_genes, group="cell_type", swap_axes=True)
plt.show()
_images/4da79d2daec2b7763fff31316d02781d4be088d9b6320586bf8b4c6adb003357.png
# ── 12.3  scale 0-1 per gene, add group color bar, full typography ─────────
fig = sv.plot_heatmap(
    ds,
    genes=heatmap_genes,
    group="cell_type",
    standard_scale="var",     # normalize each gene 0→1 across groups
    show_group_bar=True,      # color strip above/below
    cmap="Blues",
    # layout
    figsize=(8, 5),
    dpi=150,
    # typography
    title="Marker gene heatmap (scaled per gene)",
    title_fontsize=13,
    xlabel_fontsize=11,
    ylabel_fontsize=11,
    tick_fontsize=9,
    colorbar_fontsize=9,
    font_family="DejaVu Sans",
)
plt.show()
_images/6c64fee30328ab65857b9c7685e9e92930e73704805c07df1495af9e2ea5dea3.png
# ── 12.4  diverging colormap with clipped color range ─────────────────────
fig = sv.plot_heatmap(
    ds,
    genes=heatmap_genes,
    group="cell_type",
    cmap="RdBu_r",
    vmin=-1, vmax=1,          # clip color range
    figsize=(8, 4),
    dpi=150,
    title="Heatmap — diverging scale",
    title_fontsize=12,
    tick_fontsize=8,
)
plt.show()
_images/f61af1da6f015556aa04ab3660428b92e9c47859790cf2981403ef39224a7b28.png

13 · plot_matrixplot #

Color-coded grid of mean expression per gene per group, optionally annotated with the numeric value.
Cleaner than Scanpy’s matrixplot because annotation font sizes and colorbar labels are fully configurable.

matrix_genes = [f"Gene{i:03d}" for i in [0, 10, 20, 30, 40]]

# ── 13.1  default matrixplot ───────────────────────────────────────────────
fig = sv.plot_matrixplot(ds, genes=matrix_genes, group="cell_type")
plt.show()
_images/6dffdcd458f1ff24e934292ff8d8e6c1e7910afcf74783f68b5a04a1dc2a1db7.png
# ── 13.2  with numeric annotations ────────────────────────────────────────
fig = sv.plot_matrixplot(
    ds,
    genes=matrix_genes,
    group="cell_type",
    annotate=True,            # show mean expression value in each cell
    annotation_fmt=".2f",    # two decimal places
)
plt.show()
_images/14c6738f894b7c0c55e1ba7bd9e62616ec0400c151cc6a7486b58befb9cae259.png
# ── 13.3  swapped axes + full typography ──────────────────────────────────
fig = sv.plot_matrixplot(
    ds,
    genes=matrix_genes,
    group="cell_type",
    swap_axes=True,           # groups on X, genes on Y
    standard_scale="var",
    cmap="YlOrRd",
    annotate=True,
    annotation_fmt=".1f",
    # layout
    figsize=(7, 4),
    dpi=150,
    # typography
    title="Mean expression matrix",
    title_fontsize=13,
    xlabel_fontsize=11,
    ylabel_fontsize=11,
    tick_fontsize=9,
    colorbar_fontsize=9,
    font_family="DejaVu Sans",
)
plt.show()
_images/efb0f1c9925acd6b1decc9c7f040bd36e2bc9e74e7edcbb8f8e16ea665bff494.png

14 · plot_stacked_violin #

One violin per gene, stacked vertically, grouped by cell type.
Unlike Scanpy’s version, you can control violin inner style, linewidth, individual gene label sizes, and the full typography stack.

sv_genes = [f"Gene{i:03d}" for i in [0, 10, 20, 30]]

# ── 14.1  default stacked violin ──────────────────────────────────────────
fig = sv.plot_stacked_violin(ds, genes=sv_genes, group="cell_type")
plt.show()
_images/bdac0519e36eb40f1358d15e3512b83d758e0cde908c86f8dadd44d2a4914096.png
# ── 14.2  swap orientation: genes on X, groups on Y ───────────────────────
fig = sv.plot_stacked_violin(
    ds, genes=sv_genes, group="cell_type",
    swap_axes=True,
)
plt.show()
_images/a1a331b467be1758bf05c9dac71efa3769198f481bab7aa92030454af529ad5d.png
# ── 14.3  box inner, thin lines, full typography ──────────────────────────
fig = sv.plot_stacked_violin(
    ds,
    genes=sv_genes,
    group="cell_type",
    inner="box",              # "box", "quartile", "point", or None
    linewidth=0.6,
    # layout
    figsize=(8, 5),
    dpi=150,
    # typography
    title="Multi-gene expression — stacked violin",
    title_fontsize=13,
    xlabel_fontsize=11,
    ylabel_fontsize=11,
    tick_fontsize=9,
    gene_label_fontsize=10,  # gene name labels on the Y axis
    font_family="DejaVu Sans",
)
plt.show()
_images/cc5578eb80bd5b7c45047d499fa8f99d69580140b6a7bb2d9a0530430776224b.png

15 · plot_tracksplot #

Expression “tracks” — one horizontal color strip per gene, cells ordered by group.
Great for showing expression gradients across a trajectory or for comparing many genes simultaneously.
Key advantage over Scanpy: track_height, show_group_labels, and all typography params are fully adjustable.

track_genes = [f"Gene{i:03d}" for i in [0, 10, 20, 30, 40]]

# ── 15.1  default tracksplot ───────────────────────────────────────────────
fig = sv.plot_tracksplot(ds, genes=track_genes, group="cell_type")
plt.show()
_images/2796ef7c00352429062614f596d32bf3279aed263d1412923298693f714d769b.png
# ── 15.2  magma colormap, taller tracks, no group labels ──────────────────
fig = sv.plot_tracksplot(
    ds,
    genes=track_genes,
    group="cell_type",
    cmap="magma",
    track_height=0.5,         # height of each gene track in inches
    show_group_labels=False,
)
plt.show()
_images/814de0a2543fae34016ce50fddfe7c27265fc3d5b6943332c1b9079077407bb7.png
# ── 15.3  clipped range + full typography ─────────────────────────────────
fig = sv.plot_tracksplot(
    ds,
    genes=track_genes,
    group="cell_type",
    cmap="viridis",
    vmin=0, vmax=3,           # clip expression range
    track_height=0.4,
    show_group_labels=True,
    # layout
    figsize=(10, 5),
    dpi=150,
    # typography (tracksplot exposes gene/group/colorbar label sizes)
    title="Expression tracks by cell type",
    title_fontsize=13,
    gene_label_fontsize=10,
    group_label_fontsize=9,
    colorbar_fontsize=9,
)
plt.show()
_images/735fc56cf120e5a13982ab13c2e86d62ba39b6de7321310a1d0c389693c0da45.png

16 · plot_correlation #

Inter-group correlation heatmap of mean gene expression profiles.
Supports Pearson and Spearman correlation, optional numeric annotations, and full colorbar / typography control — none of which Scanpy exposes in its equivalent function.

# ── 16.1  Pearson correlation across all genes ─────────────────────────────
fig = sv.plot_correlation(ds, group="cell_type", method="pearson")
plt.show()
_images/e682ccfcfec95e3f293819a6f5383b6be7eee6dbae5607081664158e24caa0c8.png
# ── 16.2  Spearman correlation on a subset of genes ────────────────────────
corr_genes = [f"Gene{i:03d}" for i in range(20)]
fig = sv.plot_correlation(
    ds,
    group="cell_type",
    genes=corr_genes,         # restrict to these genes
    method="spearman",
)
plt.show()
_images/16db7f4e048b30b8c875aadd3dd6f0b4c7df79016642d3a62ec45b7e86cc8ca4.png
# ── 16.3  annotated + full typography ─────────────────────────────────────
fig = sv.plot_correlation(
    ds,
    group="cell_type",
    method="pearson",
    annotate=True,            # show correlation coefficient in each cell
    annotation_fmt=".2f",
    cmap="RdBu_r",
    vmin=-1, vmax=1,          # fix full [-1, 1] range for correlation
    # layout
    figsize=(6, 5),
    dpi=150,
    # typography (correlation exposes tick / colorbar / annotation sizes)
    title="Cell-type transcriptome correlation (Pearson)",
    title_fontsize=13,
    tick_fontsize=10,
    annotation_fontsize=8,
    colorbar_fontsize=9,
)
plt.show()
_images/c3fa6659b4d898a4e5d5a530bcca2aa8ee1fde72a90c13a94fd8e6a1952a5b3b.png

17 · plot_bar — grouped comparison bars #

Mean expression per group with error bars — the publication-style quantitative bar chart. Black-edged bars, optional value labels, and sortable.

# ── 17.1  mean +/- SEM, sorted, with value labels ───────────────────────────
fig = sv.plot_bar(
    ds, gene="Gene000", group="cell_type",
    error="sem",            # "sem" | "std" | "none"
    sort="descending",      # order bars by mean expression
    annotate=True,          # print each bar's mean above it
    annotation_fmt=".2f",
)
plt.show()
_images/e402a08419e8c32b61fccdfa382d5382a9adec670d66f72bbe4a54b9bdbd2986.png

18 · plot_trend — expression trend over an ordered variable #

One line per group across an ordered obs column (here the timepoint axis D0 -> D14), with shaded SEM bands. Great for developmental / pseudotime trajectories. (Gene000 was seeded to rise over time.)

# ── 18.1  trend across the ordered timepoint axis ───────────────────────────
fig = sv.plot_trend(
    ds, gene="Gene000", x="timepoint", group="cell_type",
    error="sem", show_band=True, marker="o",
)
plt.show()
_images/0181e56b54db1387b1f7843842048a97299c4d58a9675e49e48700b3bcd824c1.png

19 · plot_radar — multi-gene signature radar #

Compare several genes’ mean expression across groups as polygons. scale="var" normalizes each gene to [0, 1] so the axes are comparable.

# ── 19.1  signature radar across cell types ─────────────────────────────────
radar_genes = ["Gene000", "Gene010", "Gene020", "Gene030", "Gene001", "Gene011"]
fig = sv.plot_radar(ds, radar_genes, group="cell_type", scale="var")
plt.show()
_images/7eeff3320f705d0b73bdf9c4f571f8b45e5f0863dcf63052fd87d33b9af0dede.png

20 · plot_embedding_3d — 3-D embedding scatter #

Scatter the first three dimensions of a 3-D embedding (here X_pca), colored by a metadata column or by gene expression. Tune the camera with elev / azim.

# ── 20.1  colored by cell type ──────────────────────────────────────────────
fig = sv.plot_embedding_3d(
    ds, color="cell_type", embedding="X_pca",
    elev=22, azim=-60, point_size=12,
)
plt.show()

# ── 20.2  colored by gene expression ────────────────────────────────────────
fig = sv.plot_embedding_3d(ds, gene="Gene000", embedding="X_pca", point_size=12)
plt.show()
_images/b009b0a3ef5c59c6be04293ce58d3b8a8b57ab87c5f89686b6f92c0248190023.png _images/7c7133656fc2ef5d4382188449e52cb88a02d8d2aa5b1715c4eb50f0fa0b7411.png