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#
plot_embedding— UMAP / t-SNE scatterplot_multigene— multi-gene expression gridplot_violin— violin / box plotplot_dotplot— dot plotplot_composition— stacked barplot_heatmap— gene × group heatmapplot_matrixplot— mean expression matrixplot_stacked_violin— multi-gene violin stackplot_tracksplot— single-cell expression tracksplot_correlation— inter-group correlation heatmapplot_bar— grouped comparison bars (± error)plot_trend— expression trend over an ordered variableplot_radar— multi-gene signature radarplot_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()
# ── 4.2 color by gene expression ────────────────────────────────────────
fig = sv.plot_embedding(ds, gene="Gene000")
plt.show()
# ── 4.3 t-SNE instead of UMAP ───────────────────────────────────────────
fig = sv.plot_embedding(ds, color="cell_type", embedding="X_tsne")
plt.show()
# ── 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()
# ── 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()
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()
# ── 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()
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()
# ── 6.2 box plot with data points ────────────────────────────────────────
fig = sv.plot_violin(
ds,
gene="Gene000",
group="cell_type",
kind="box",
show_points=True,
)
plt.show()
# ── 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()
# ── 6.4 split by batch ───────────────────────────────────────────────────
fig = sv.plot_violin(ds, gene="Gene005", group="batch")
plt.show()
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()
# ── 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()
# ── 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()
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()
# ── 8.2 raw cell counts ─────────────────────────────────────────────────
fig = sv.plot_composition(ds, group="cell_type", split="batch", normalize=False)
plt.show()
# ── 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()
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
# ── 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()
# ── 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()
# ── 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()
# ── 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 |
|---|---|---|---|
|
|
all |
Figure width × height in inches |
|
|
all |
Resolution (dots per inch) |
|
|
all |
Figure title text |
|
|
all |
Title font size |
|
|
violin, dotplot, composition, heatmap, matrixplot, stacked_violin, tracksplot |
Axis label text |
|
|
violin, dotplot, composition, heatmap, matrixplot, stacked_violin, tracksplot |
Axis label font size |
|
|
all |
Tick-label font size |
|
|
embedding, dotplot, composition |
Legend entry font size |
|
|
embedding (gene), multigene, dotplot, heatmap, matrixplot, tracksplot, correlation |
Colorbar text size |
|
|
embedding |
Centroid text label size |
|
|
multigene |
Per-panel title size |
|
|
multigene |
Figure super-title size |
|
|
dotplot |
X-axis gene label rotation (°) |
|
|
stacked_violin |
Gene label font size on Y axis |
|
|
violin, composition |
X-tick rotation (°) |
|
|
all |
Per-figure font family |
|
|
embedding, multigene |
Scatter point diameter |
|
|
embedding, multigene |
Point transparency |
|
|
embedding, multigene, dotplot, heatmap, matrixplot, tracksplot, correlation |
Matplotlib colormap |
|
|
heatmap, matrixplot, tracksplot, correlation |
Clip color range |
|
|
dotplot, heatmap, matrixplot |
|
|
|
heatmap, matrixplot, stacked_violin |
Transpose gene/group axes |
|
|
heatmap |
Show group color strip |
|
|
matrixplot, correlation |
Overlay numeric values |
|
|
matrixplot, correlation |
Python format string, e.g. |
|
|
stacked_violin |
Violin inner: |
|
|
stacked_violin |
Violin outline width |
|
|
tracksplot |
Height of each gene track (inches) |
|
|
tracksplot |
Label group boundaries |
|
|
correlation |
|
|
|
violin |
|
|
|
violin |
Overlay jittered data points |
|
|
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()
# ── 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()
# ── 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()
# ── 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()
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()
# ── 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()
# ── 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()
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()
# ── 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()
# ── 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()
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()
# ── 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()
# ── 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()
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()
# ── 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()
# ── 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()
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()
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()
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()
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()