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.
Quick reference
Section titled “Quick reference”| 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 adimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport scanpy as sc
sc.settings.verbosity = 0Path("outputs").mkdir(exist_ok=True)pd.set_option("display.width", 100)AnnData
Section titled “AnnData”| 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 |
Build one from arrays
Section titled “Build one from arrays”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 LYZcell_1 0.0 3.0 1.0cell_2 2.0 0.0 0.0Read a 10x matrix
Section titled “Read a 10x matrix”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_idsMIR1302-10 ENSG00000243485FAM138A ENSG00000237613OR4F5 ENSG00000186092Gene symbols are not unique. make_unique=True, the default, renames duplicates with a
suffix such as -1.
Combine samples with ad.concat
Section titled “Combine samples with ad.concat”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)samplesample_a 1350sample_b 1350Name: count, dtype: int64['AAACATACAACCAC-1-sample_a', 'AAACATTGAGCTAC-1-sample_a']Quality control
Section titled “Quality control”calculate_qc_metrics
Section titled “calculate_qc_metrics”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_mtcount 2700.0 2700.0 2700.0mean 847.0 2366.9 2.2std 282.1 1094.3 1.2min 212.0 548.0 0.025% 690.0 1757.8 1.550% 817.0 2197.0 2.075% 953.2 2763.0 2.6max 3422.0 15844.0 22.6QC violin plot
Section titled “QC violin plot”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")
Filter cells and genes
Section titled “Filter cells and genes”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 genesIndexing an AnnData returns a view. .copy() turns it into a new object, which avoids an
ImplicitModificationWarning when you add a column later.
Doublet detection with scrublet
Section titled “Doublet detection with scrublet”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.000mean 0.055std 0.041min 0.00625% 0.02950% 0.04575% 0.067max 0.415Name: doublet_score, dtype: float64samplesample_a 16sample_b 11Name: predicted_doublet, dtype: int642611 cells after removing predicted doubletsNormalization and feature selection
Section titled “Normalization and feature selection”normalize_total and log1p
Section titled “normalize_total and log1p”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)highly_variable_genes
Section titled “highly_variable_genes”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: 2000Dimensionality reduction and clustering
Section titled “Dimensionality reduction and clustering”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]Neighbor graph
Section titled “Neighbor graph”Clustering and UMAP both read this graph from adata.obsp.
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30, random_state=42)Leiden clustering
Section titled “Leiden clustering”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())leiden0 3311 3342 11153 5134 1585 1496 11Name: count, dtype: int64sc.tl.umap(adata, random_state=42)print(f"UMAP coordinates: {adata.obsm['X_umap'].shape}")UMAP coordinates: (2611, 2)Marker genes
Section titled “Marker genes”rank_genes_groups
Section titled “rank_genes_groups”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 60 CCL5 CD74 LDHB LYZ GNLY LST1 SPARC1 NKG7 CD79A RPS12 S100A9 NKG7 FCER1G PF42 B2M HLA-DRA RPS25 CST3 GZMB FCGR3A PPBP3 IL32 CD79B RPS27 TYROBP PRF1 AIF1 GNG114 GZMA HLA-DPB1 RPS6 S100A8 CTSW COTL1 SDPRResults as a table
Section titled “Results as a table”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_adj0 CCL5 27.2 5.94 2.03e-162 2.78e-1581 NKG7 23.3 5 4.56e-120 3.13e-1162 B2M 19.1 0.749 1.96e-81 8.96e-783 IL32 18.8 2.72 4.81e-79 1.65e-754 GZMA 18.6 4.04 3.68e-77 1.01e-73Dot plot of known markers
Section titled “Dot plot of known markers”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")
Annotate clusters
Section titled “Annotate clusters”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_typeCD4 T 1115CD14 monocyte 513B 334CD8 T 331NK 158FCGR3A monocyte 149Platelet 11Name: count, dtype: int64fig, 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)
Matrix plot by cell type
Section titled “Matrix plot by cell type”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")
Cell cycle scoring
Section titled “Cell cycle scoring”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 43G2M genes found: 44 of 54phase G1 G2M Scell_typeCD8 T 189 17 125B 197 15 122CD4 T 658 52 405CD14 monocyte 407 24 82NK 96 6 56FCGR3A monocyte 115 8 26Platelet 6 5 0 S_score G2M_scorephaseG1 -0.041 -0.086G2M -0.033 0.021S 0.031 -0.084A 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.
Pseudobulk with sc.get.aggregate
Section titled “Pseudobulk with sc.get.aggregate”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 LYZsample_a_CD8 T 261.0 11.0 98.0sample_a_B 18.0 404.0 105.0sample_a_CD4 T 1046.0 26.0 408.0sample_a_CD14 monocyte 27.0 17.0 11991.0sample_a_NK 61.0 5.0 45.0sample_a_FCGR3A monocyte 13.0 8.0 678.0sample_a_Platelet 0.0 0.0 4.0sample_b_CD8 T 245.0 7.0 91.0sample_b_B 20.0 340.0 101.0sample_b_CD4 T 987.0 30.0 412.0sample_b_CD14 monocyte 25.0 13.0 12079.0sample_b_NK 47.0 4.0 41.0sample_b_FCGR3A monocyte 15.0 6.0 674.0sample_b_Platelet 1.0 0.0 2.0Subset and extract
Section titled “Subset and extract”By cells, by genes
Section titled “By cells, by genes”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 genesthree genes: (2611, 3), view: Truesc.get.obs_df
Section titled “sc.get.obs_df”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 LYZcell_typeCD8 T 1.65 0.09 0.83B 0.18 2.17 0.87CD4 T 1.72 0.08 0.96CD14 monocyte 0.15 0.09 5.03NK 0.86 0.10 0.82FCGR3A monocyte 0.22 0.12 3.03Platelet 0.26 0.00 1.05Write and read h5ad
Section titled “Write and read h5ad”.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)See also
Section titled “See also”- The AnnData Object
- Quality Control
- Normalization
- Dimensionality Reduction
- Clustering
- Annotation
- Seurat cheatsheet
Scientific references
Section titled “Scientific references”Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.
Further reading
Section titled “Further reading”-
Scanpy preprocessing and clustering
The guide explains quality metrics, neighbor graphs, cluster resolution, and marker inspection.
-
The tutorial explains the S and G2M lists and the reference-gene scores used for phase labels.
-
The deposit identifies the original donor, 2,700 cells, Cell Ranger version, and dataset terms.