Skip to content

Scanpy

Scanpy runs the standard single-cell RNA-seq workflow in Python, from a count matrix to annotated clusters. It stores everything in one AnnData object: the matrix, the cell and gene tables, the embeddings, and the neighbor graph. The examples use the PBMC 3k dataset from 10x Genomics, 2,700 peripheral blood mononuclear cells from one healthy donor, as the filtered gene-barcode matrix from Cell Ranger. Every block below ran with Scanpy 1.12 and anndata 0.13.

Step Call
Read 10x folder sc.read_10x_mtx(path, var_names="gene_symbols")
Read 10x h5 sc.read_10x_h5(path)
Combine samples ad.concat({"a": a, "b": b}, label="sample", index_unique="-")
QC metrics sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"])
Filter sc.pp.filter_cells(adata, min_genes=200)
Doublets sc.pp.scrublet(adata, batch_key="sample")
Normalize sc.pp.normalize_total(adata, target_sum=1e4)
Log transform sc.pp.log1p(adata)
Variable genes sc.pp.highly_variable_genes(adata, n_top_genes=2000)
PCA sc.pp.pca(adata, mask_var="highly_variable")
Neighbors sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30)
Leiden sc.tl.leiden(adata, flavor="igraph", n_iterations=2, directed=False)
UMAP sc.tl.umap(adata)
Markers sc.tl.rank_genes_groups(adata, "leiden", method="wilcoxon")
Marker table sc.get.rank_genes_groups_df(adata, group="0")
Dot plot sc.pl.dotplot(adata, genes, groupby="leiden", show=False)
Matrix plot sc.pl.matrixplot(adata, genes, groupby=..., standard_scale="var")
Cell cycle sc.tl.score_genes_cell_cycle(adata, s_genes=..., g2m_genes=...)
Pseudobulk sc.get.aggregate(adata, by=["sample", "cell_type"], func="sum")
Expression table sc.get.obs_df(adata, keys=[...])
Save adata.write_h5ad("file.h5ad", compression="gzip")
Load ad.read_h5ad("file.h5ad")
from pathlib import Path
import anndata as ad
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scanpy as sc
sc.settings.verbosity = 0
Path("outputs").mkdir(exist_ok=True)
pd.set_option("display.width", 100)
Slot What it holds
adata.X the main matrix, cells in rows and genes in columns
adata.obs one row per cell: QC metrics, clusters, labels
adata.var one row per gene: IDs, highly variable flags
adata.layers other matrices of the same shape, such as raw counts
adata.obsm per-cell embeddings: X_pca, X_umap
adata.obsp cell by cell graphs: distances, connectivities
adata.uns everything else: parameters, colors, marker results
toy = ad.AnnData(
X=np.array([[0, 3, 1], [2, 0, 0]], dtype=np.float32),
obs=pd.DataFrame({"donor": ["d1", "d2"]}, index=["cell_1", "cell_2"]),
var=pd.DataFrame(index=["CD3E", "MS4A1", "LYZ"]),
)
print(toy)
print(toy.to_df())
AnnData object with n_obs × n_vars = 2 × 3
obs: 'donor'
layers: None (.X)
CD3E MS4A1 LYZ
cell_1 0.0 3.0 1.0
cell_2 2.0 0.0 0.0

read_10x_mtx takes the folder that holds matrix.mtx, genes.tsv or features.tsv.gz, and barcodes.tsv. Download pbmc3k_filtered_gene_bc_matrices.tar.gz from 10x Genomics and point the call at its hg19 folder, or call sc.datasets.pbmc3k(), which downloads the same data. For a Cell Ranger .h5 file, use sc.read_10x_h5.

The source matrix is 10x Genomics’ PBMC 3k dataset, released in 2016 under CC BY 4.0. This lesson converts the matrix to AnnData, divides its cells into artificial sample groups, and derives the displayed analysis results.

adata = sc.read_10x_mtx("/opt/data/pbmc3k", var_names="gene_symbols")
print(adata)
print(adata.var.head(3))
AnnData object with n_obs × n_vars = 2700 × 32738
var: 'gene_ids'
layers: None (.X)
gene_ids
MIR1302-10 ENSG00000243485
FAM138A ENSG00000237613
OR4F5 ENSG00000186092

Gene symbols are not unique. make_unique=True, the default, renames duplicates with a suffix such as -1.

PBMC 3k is one sample, so here the first 1,350 and the last 1,350 barcodes stand in for two samples. label adds a column that names the source of each cell, index_unique appends that name to the barcodes so they stay unique, and merge="same" keeps the gene columns that agree across samples. The rest of the page runs on the combined object.

adata = ad.concat(
{"sample_a": adata[:1350], "sample_b": adata[1350:]},
label="sample", index_unique="-", merge="same",
)
print(adata)
print(adata.obs["sample"].value_counts())
print(adata.obs_names[:2].tolist())
AnnData object with n_obs × n_vars = 2700 × 32738
obs: 'sample'
var: 'gene_ids'
layers: None (.X)
sample
sample_a 1350
sample_b 1350
Name: count, dtype: int64
['AAACATACAACCAC-1-sample_a', 'AAACATTGAGCTAC-1-sample_a']

Flag the mitochondrial genes and compute per-cell totals. A high mitochondrial fraction marks broken cells that lost their cytoplasmic RNA.

adata.var["mt"] = adata.var_names.str.startswith("MT-")
sc.pp.calculate_qc_metrics(
adata, qc_vars=["mt"], percent_top=None, log1p=False, inplace=True
)
qc_cols = ["n_genes_by_counts", "total_counts", "pct_counts_mt"]
print(adata.obs[qc_cols].describe().round(1))
n_genes_by_counts total_counts pct_counts_mt
count 2700.0 2700.0 2700.0
mean 847.0 2366.9 2.2
std 282.1 1094.3 1.2
min 212.0 548.0 0.0
25% 690.0 1757.8 1.5
50% 817.0 2197.0 2.0
75% 953.2 2763.0 2.6
max 3422.0 15844.0 22.6

Scanpy plots take show=False so the figure stays open for plt.savefig. The jitter of the points comes from NumPy’s global random state, so seed it for a figure that repeats.

np.random.seed(42)
sc.pl.violin(adata, qc_cols, jitter=0.4, multi_panel=True, show=False)
plt.savefig("outputs/scanpy-qc-violin.png", dpi=150, bbox_inches="tight")
plt.close("all")

Three violin plots of the 2,700 unfiltered cells. Genes per cell center near 800 and reach 3,422. Total counts center near 2,200 and reach 15,844. The mitochondrial percentage sits mostly below 5 and reaches 22.6.

The thresholds follow the original PBMC 3k tutorial: at least 200 genes per cell, genes seen in at least 3 cells, fewer than 2,500 genes to drop likely doublets, and under 5% mitochondrial counts.

sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_genes(adata, min_cells=3)
keep = (adata.obs["n_genes_by_counts"] < 2500) & (
adata.obs["pct_counts_mt"] < 5
)
adata = adata[keep].copy()
print(f"{adata.n_obs} cells x {adata.n_vars} genes")
2638 cells x 13714 genes

Indexing an AnnData returns a view. .copy() turns it into a new object, which avoids an ImplicitModificationWarning when you add a column later.

sc.pp.scrublet simulates doublets from pairs of cells and scores each real cell by how many simulated doublets sit among its neighbors. Run it on raw counts, one sample at a time with batch_key. Without threshold, Scrublet picks the cut from the score histogram and needs scikit-image, which this container does not have, so the block sets the cut at 0.25.

sc.pp.scrublet(adata, batch_key="sample", threshold=0.25, random_state=42)
print(adata.obs["doublet_score"].describe().round(3))
print(adata.obs.groupby("sample", observed=True)["predicted_doublet"].sum())
adata = adata[~adata.obs["predicted_doublet"]].copy()
print(f"{adata.n_obs} cells after removing predicted doublets")
count 2638.000
mean 0.055
std 0.041
min 0.006
25% 0.029
50% 0.045
75% 0.067
max 0.415
Name: doublet_score, dtype: float64
sample
sample_a 16
sample_b 11
Name: predicted_doublet, dtype: int64
2611 cells after removing predicted doublets

Keep the raw counts in a layer first. Count-based methods and pseudobulk need them later.

adata.layers["counts"] = adata.X.copy()
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)

The default flavor="seurat" works on log-normalized data. flavor="seurat_v3" works on counts and needs layer="counts".

sc.pp.highly_variable_genes(adata, n_top_genes=2000, flavor="seurat")
print(f"highly variable genes: {adata.var['highly_variable'].sum()}")
highly variable genes: 2000

mask_var="highly_variable" restricts PCA to the selected genes. Older tutorials pass use_highly_variable=True, which Scanpy 1.12 still runs with a deprecation warning, and call sc.tl.pca, which is now the same function as sc.pp.pca.

sc.pp.pca(adata, n_comps=50, mask_var="highly_variable", random_state=42)
variance_ratio = adata.uns["pca"]["variance_ratio"]
print(f"variance ratio, PC1 to PC5: {variance_ratio[:5].round(4)}")
variance ratio, PC1 to PC5: [0.1023 0.0357 0.0245 0.0113 0.0075]

Clustering and UMAP both read this graph from adata.obsp.

sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30, random_state=42)

Scanpy 1.12 still defaults to the leidenalg backend and warns that the default will move to igraph. Pass flavor="igraph", n_iterations=2, and directed=False to get the future default now. Raise resolution for more, smaller clusters.

sc.tl.leiden(
adata, resolution=0.5, flavor="igraph", n_iterations=2,
directed=False, random_state=42,
)
print(adata.obs["leiden"].value_counts().sort_index())
leiden
0 331
1 334
2 1115
3 513
4 158
5 149
6 11
Name: count, dtype: int64
sc.tl.umap(adata, random_state=42)
print(f"UMAP coordinates: {adata.obsm['X_umap'].shape}")
UMAP coordinates: (2611, 2)

The Wilcoxon test compares each cluster against all other cells. The top five names per cluster are usually enough to name a cell type.

sc.tl.rank_genes_groups(adata, "leiden", method="wilcoxon")
top_markers = pd.DataFrame(adata.uns["rank_genes_groups"]["names"]).head(5)
print(top_markers)
0 1 2 3 4 5 6
0 CCL5 CD74 LDHB LYZ GNLY LST1 SPARC
1 NKG7 CD79A RPS12 S100A9 NKG7 FCER1G PF4
2 B2M HLA-DRA RPS25 CST3 GZMB FCGR3A PPBP
3 IL32 CD79B RPS27 TYROBP PRF1 AIF1 GNG11
4 GZMA HLA-DPB1 RPS6 S100A8 CTSW COTL1 SDPR

sc.get.rank_genes_groups_df returns the scores, log fold changes, and adjusted p-values for one cluster as a DataFrame.

cluster_0 = sc.get.rank_genes_groups_df(adata, group="0")
print(cluster_0.head(5).to_string(float_format="{:.3g}".format))
names scores logfoldchanges pvals pvals_adj
0 CCL5 27.2 5.94 2.03e-162 2.78e-158
1 NKG7 23.3 5 4.56e-120 3.13e-116
2 B2M 19.1 0.749 1.96e-81 8.96e-78
3 IL32 18.8 2.72 4.81e-79 1.65e-75
4 GZMA 18.6 4.04 3.68e-77 1.01e-73

Dot size is the fraction of cells in the cluster that express the gene, and color is the mean expression.

marker_genes = {
"T": ["CD3E", "IL7R", "CD8A"],
"B": ["MS4A1", "CD79A"],
"NK": ["GNLY", "NKG7"],
"Mono": ["CD14", "LYZ", "FCGR3A"],
"DC": ["FCER1A"],
"Platelet": ["PPBP"],
}
sc.pl.dotplot(adata, marker_genes, groupby="leiden", show=False)
plt.savefig("outputs/scanpy-dotplot.png", dpi=150, bbox_inches="tight")
plt.close("all")

Dot plot of 14 marker genes across Leiden clusters 0 to 6. CD3E and IL7R mark clusters 0 and 2, and cluster 0 also expresses CD8A and NKG7. MS4A1 and CD79A mark cluster 1, CD14 and a strong LYZ mark cluster 3, and GNLY, NKG7, and FCGR3A mark cluster 4. LYZ and FCGR3A mark cluster 5, and PPBP marks cluster 6. FCER1A shows only small dots in every cluster.

Map each cluster to a cell type from its markers. The mapping below was read from the marker table and the dot plot of this run: IL7R for CD4 T cells, CD8A and NKG7 for CD8 T cells, GNLY for NK cells, and PPBP for the 11 platelets. FCER1A, the dendritic cell marker, does not mark a cluster of its own at this resolution. Cluster numbers can change with the Scanpy version or the parameters, so check the markers before you reuse a mapping.

cluster_to_type = {
"0": "CD8 T",
"1": "B",
"2": "CD4 T",
"3": "CD14 monocyte",
"4": "NK",
"5": "FCGR3A monocyte",
"6": "Platelet",
}
adata.obs["cell_type"] = (
adata.obs["leiden"].map(cluster_to_type).astype("category")
)
print(adata.obs["cell_type"].value_counts())
cell_type
CD4 T 1115
CD14 monocyte 513
B 334
CD8 T 331
NK 158
FCGR3A monocyte 149
Platelet 11
Name: count, dtype: int64
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
sc.pl.umap(adata, color="leiden", legend_loc="on data", frameon=False,
title="Leiden clusters", ax=axes[0], show=False)
sc.pl.umap(adata, color="cell_type", frameon=False, title="Cell type",
ax=axes[1], show=False)
fig.savefig("outputs/scanpy-umap.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Two UMAP panels of the 2,611 cells left after QC and doublet removal. Left, the seven Leiden clusters are labeled on the embedding. Cluster 2 forms a large island with cluster 0 above it and cluster 4 at the top, cluster 1 forms a separate island at the bottom, and clusters 3, 5, and 6 form a group on the left. Right, the same cells are colored by cell type: CD8 T, B, CD4 T, CD14 monocyte, NK, FCGR3A monocyte, and a small platelet group at the top left.

sc.pl.matrixplot shows one colored cell per group and gene. standard_scale="var" scales each gene from 0 to 1 across the groups, so a weak marker reads as clearly as a strong one. sc.pl.stacked_violin takes the same arguments and draws a violin in each cell instead. FCER1A, the dendritic cell marker, is highest in the CD14 monocyte group, which suggests the few dendritic cells sit inside that cluster at this resolution.

sc.pl.matrixplot(adata, marker_genes, groupby="cell_type",
standard_scale="var", colorbar_title="scaled mean",
show=False)
plt.savefig("outputs/scanpy-matrixplot.png", dpi=150, bbox_inches="tight")
plt.close("all")

Matrix plot of 14 marker genes, each scaled from 0 to 1, across seven cell types. CD3E is at the top in both T cell groups, IL7R in CD4 T cells, and CD8A in CD8 T cells. MS4A1 and CD79A peak in B cells, GNLY and NKG7 in NK cells, CD14, LYZ, and FCER1A in CD14 monocytes, FCGR3A in FCGR3A monocytes, and PPBP in platelets.

sc.tl.score_genes_cell_cycle scores each cell against the S phase and G2M gene lists from Tirosh et al. 2016, the same lists as Seurat’s cc.genes, and calls a phase. Keep only the genes present in the data.

The 43 S-phase and 54 G2M genes below match Seurat 5.6.0’s cc.genes object, including its original symbols and list order. Its data reference credits Tirosh and colleagues, 2016. The Seurat 5.6.0 source distribution includes this object under MIT; the complete notice credits the Seurat authors. This lesson filters the lists to genes present in the matrix and derives phase scores.

s_genes_all = [
"MCM5", "PCNA", "TYMS", "FEN1", "MCM2", "MCM4", "RRM1", "UNG", "GINS2",
"MCM6", "CDCA7", "DTL", "PRIM1", "UHRF1", "MLF1IP", "HELLS", "RFC2",
"RPA2", "NASP", "RAD51AP1", "GMNN", "WDR76", "SLBP", "CCNE2", "UBR7",
"POLD3", "MSH2", "ATAD2", "RAD51", "RRM2", "CDC45", "CDC6", "EXO1",
"TIPIN", "DSCC1", "BLM", "CASP8AP2", "USP1", "CLSPN", "POLA1", "CHAF1B",
"BRIP1", "E2F8",
]
g2m_genes_all = [
"HMGB2", "CDK1", "NUSAP1", "UBE2C", "BIRC5", "TPX2", "TOP2A", "NDC80",
"CKS2", "NUF2", "CKS1B", "MKI67", "TMPO", "CENPF", "TACC3", "FAM64A",
"SMC4", "CCNB2", "CKAP2L", "CKAP2", "AURKB", "BUB1", "KIF11", "ANP32E",
"TUBB4B", "GTSE1", "KIF20B", "HJURP", "CDCA3", "HN1", "CDC20", "TTK",
"CDC25C", "KIF2C", "RANGAP1", "NCAPD2", "DLGAP5", "CDCA2", "CDCA8",
"ECT2", "KIF23", "HMMR", "AURKA", "PSRC1", "ANLN", "LBR", "CKAP5",
"CENPE", "CTCF", "NEK2", "G2E3", "GAS2L3", "CBX5", "CENPA",
]
s_genes = [gene for gene in s_genes_all if gene in adata.var_names]
g2m_genes = [gene for gene in g2m_genes_all if gene in adata.var_names]
print(f"S genes found: {len(s_genes)} of {len(s_genes_all)}")
print(f"G2M genes found: {len(g2m_genes)} of {len(g2m_genes_all)}")
sc.tl.score_genes_cell_cycle(adata, s_genes=s_genes, g2m_genes=g2m_genes)
print(pd.crosstab(adata.obs["cell_type"], adata.obs["phase"]))
phase_scores = adata.obs.groupby("phase", observed=True)[
["S_score", "G2M_score"]
].median()
print(phase_scores.round(3))
S genes found: 36 of 43
G2M genes found: 44 of 54
phase G1 G2M S
cell_type
CD8 T 189 17 125
B 197 15 122
CD4 T 658 52 405
CD14 monocyte 407 24 82
NK 96 6 56
FCGR3A monocyte 115 8 26
Platelet 6 5 0
S_score G2M_score
phase
G1 -0.041 -0.086
G2M -0.033 0.021
S 0.031 -0.084

A cell gets an S or G2M call as soon as that score is above zero and above the other score. Here the cells called S have a median S score of 0.031, just above zero, so many of those calls in resting blood cells rest on weak scores rather than on a clear cycling signal.

sc.get.aggregate sums the raw counts of every cell in each sample and cell type, the input that DESeq2 or edgeR expect for a differential expression test between conditions. The result is a new AnnData with one row per group and the sums in layers["sum"].

pseudobulk = sc.get.aggregate(
adata, by=["sample", "cell_type"], func="sum", layer="counts"
)
print(pseudobulk)
print(pseudobulk.to_df(layer="sum")[["CD3E", "MS4A1", "LYZ"]])
AnnData object with n_obs × n_vars = 14 × 13714
obs: 'sample', 'cell_type', 'n_obs_aggregated'
var: 'gene_ids', 'mt', 'n_cells_by_counts', 'mean_counts', 'pct_dropout_by_counts', 'total_counts', 'n_cells', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
layers: 'sum'
CD3E MS4A1 LYZ
sample_a_CD8 T 261.0 11.0 98.0
sample_a_B 18.0 404.0 105.0
sample_a_CD4 T 1046.0 26.0 408.0
sample_a_CD14 monocyte 27.0 17.0 11991.0
sample_a_NK 61.0 5.0 45.0
sample_a_FCGR3A monocyte 13.0 8.0 678.0
sample_a_Platelet 0.0 0.0 4.0
sample_b_CD8 T 245.0 7.0 91.0
sample_b_B 20.0 340.0 101.0
sample_b_CD4 T 987.0 30.0 412.0
sample_b_CD14 monocyte 25.0 13.0 12079.0
sample_b_NK 47.0 4.0 41.0
sample_b_FCGR3A monocyte 15.0 6.0 674.0
sample_b_Platelet 1.0 0.0 2.0

A boolean mask on obs selects cells and a list of names selects genes.

b_cells = adata[adata.obs["cell_type"] == "B"].copy()
three_genes = adata[:, ["CD3E", "MS4A1", "LYZ"]]
print(f"B cells: {b_cells.n_obs} cells x {b_cells.n_vars} genes")
print(f"three genes: {three_genes.shape}, view: {three_genes.is_view}")
B cells: 334 cells x 13714 genes
three genes: (2611, 3), view: True

Pull cell metadata and gene expression into one DataFrame for pandas or plotting.

expr_df = sc.get.obs_df(adata, keys=["cell_type", "CD3E", "MS4A1", "LYZ"])
print(expr_df.groupby("cell_type", observed=True).mean().round(2))
CD3E MS4A1 LYZ
cell_type
CD8 T 1.65 0.09 0.83
B 0.18 2.17 0.87
CD4 T 1.72 0.08 0.96
CD14 monocyte 0.15 0.09 5.03
NK 0.86 0.10 0.82
FCGR3A monocyte 0.22 0.12 3.03
Platelet 0.26 0.00 1.05

.h5ad stores the whole object, layers and graphs included, in one HDF5 file. adata.write("file.h5ad") in older code is the same call. Pass backed="r" to ad.read_h5ad to leave X on disk for a dataset larger than memory.

adata.write_h5ad("outputs/scanpy-pbmc3k.h5ad", compression="gzip")
reloaded = ad.read_h5ad("outputs/scanpy-pbmc3k.h5ad")
print(reloaded)
AnnData object with n_obs × n_vars = 2611 × 13714
obs: 'sample', 'n_genes_by_counts', 'total_counts', 'total_counts_mt', 'pct_counts_mt', 'n_genes', 'doublet_score', 'predicted_doublet', 'leiden', 'cell_type', 'S_score', 'G2M_score', 'phase'
var: 'gene_ids', 'mt', 'n_cells_by_counts', 'mean_counts', 'pct_dropout_by_counts', 'total_counts', 'n_cells', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
uns: 'cell_type_colors', 'hvg', 'leiden', 'leiden_colors', 'log1p', 'neighbors', 'pca', 'rank_genes_groups', 'scrublet', 'umap'
obsm: 'X_pca', 'X_umap'
varm: 'PCs'
obsp: 'connectivities', 'distances'
layers: 'counts', None (.X)

Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.