Single-cell transcriptomics / Seurat and Scanpy

Single-cell analysis with Seurat v5 and Scanpy

People who get 10x single-cell data often stall once the matrix is loaded: which cells to keep, how to set thresholds, and what to call each cluster. This page uses PBMC 3k as an example, explains why each step is done and what to check, and puts errors in the troubleshooting section.

Short answer

The main line of single-cell analysis is: load the Cell Ranger matrix, remove doublets, remove low-quality cells, normalize and reduce dimensions, cluster, then name each cluster with marker genes. There is no single correct threshold or resolution; choose them from the data distribution and cluster stability.

About this page

Tutorial
What this page solves
You have 10x single-cell sequencing data and want to know which cell types are in the sample and how many cells each type has. This page uses the public PBMC 3k dataset to take you from the Cell Ranger output to named cell clusters, one step at a time.
Who it is for
Graduate students and researchers doing single-cell analysis for the first time. You can read and write tables in R or Python, but you have not yet done QC or clustering on single-cell data.
What you will have
After reading, you will have a Seurat object with doublet labels, QC results and clustering, a marker gene table for each cluster, and cluster names based on those markers.
Covers
  • Seurat v5 from Cell Ranger output to cell clusters and cluster names, with the purpose and a check for each step
  • The same workflow in Scanpy, and how the two compare and convert
  • Multi-sample integration, large datasets, and what to do when memory is short, as branches
  • Common errors and old-tutorial pitfalls on v5, collected in the troubleshooting section
Does not cover
  • Running Cell Ranger alignment and its parameters; this page assumes you already have its output
  • Downstream analyses such as enrichment, differential expression and trajectories; see related guides
  • Cell-cell communication analysis; see the CellChat tutorial
  • Spatial transcriptomics and single-cell ATAC data

Main steps

Step 1

Why this stepThis step reads the Cell Ranger count matrix into a Seurat object. Every later step works on this object, so first confirm that the cell and gene counts are right.

In the count matrix, each row is a gene and each column is a cell. Each number is the UMI count, the number of molecules detected for that gene in that cell.

Read the filtered_feature_bc_matrix directory or the .h5 file with the same name. It has already had empty droplets removed. raw_feature_bc_matrix is only needed for ambient RNA correction; see the branch on other tools.

Seurat v5 stores the expression matrix in layers: counts holds raw counts and data holds normalized values. Use the layer argument to access them. The v4 slot argument no longer works; see troubleshooting for the errors.

Read the data and create the object (PBMC 3k, tested on this page)r
# Seurat v5: read the Cell Ranger output and create the object
library(Seurat)
counts <- Read10X("filtered_gene_bc_matrices/hg19")      # Cell Ranger >= 3: Read10X_h5("filtered_feature_bc_matrix.h5")
obj <- CreateSeuratObject(counts, project = "pbmc3k", min.cells = 3, min.features = 200)
obj[["percent.mt"]] <- PercentageFeatureSet(obj, pattern = "^MT-")   # mouse: "^mt-"
  1. 01

    Read the matrix

    Read10X reads the directory. Cell Ranger 3 and later can also read the h5 file with Read10X_h5.

  2. 02

    Create the object

    CreateSeuratObject drops genes detected in fewer than 3 cells and cells with fewer than 200 detected genes.

  3. 03

    Compute the mitochondrial fraction

    PercentageFeatureSet computes the percentage of total UMIs from genes starting with MT- and stores it in percent.mt. For mouse data use ^mt-.

Step 2

Why this stepA doublet is a fake cell formed when two cells are captured in the same droplet. It expresses markers of both cell types, so it can be mistaken for a new cell type. Flag doublets before QC.

scDblFinder simulates doublets from the raw counts, then checks whether each cell looks like a simulated doublet. Run it separately for each 10x sample; for multiple samples, use the samples argument to separate them.

The code on this page removes cells labeled as doublets directly. For whether to remove whole clusters instead, see the judgement section.

Flag doublets with scDblFinder (tested on this page)r
# Doublets: scDblFinder on the raw counts of each capture, before strict QC
library(scDblFinder); library(SingleCellExperiment)
set.seed(1)
sce <- scDblFinder(SingleCellExperiment(list(counts = LayerData(obj, layer = "counts"))))
obj$dbl_class <- sce$scDblFinder.class               # several captures: scDblFinder(sce, samples = "sample")

Step 3

Why this stepQC removes three kinds of cells: those with almost no signal, those with abnormally high gene or UMI counts, and those with an abnormally high mitochondrial fraction. Thresholds must come from your own data distribution; fixed numbers from a tutorial only suit that tutorial's data.

Tutorials often use fixed thresholds of 200, 2500 and 5%; this page computes thresholds from the data distribution with MAD. MAD is the median absolute deviation, a measure of spread that extreme values do not easily distort. Thresholds are the median plus or minus a multiple of MAD; the multiples are in the table above.

Cells with a high mitochondrial fraction are usually cells whose membrane is broken and whose cytoplasmic mRNA has leaked out, so mainly mitochondrial mRNA remains. For this metric, the threshold must also be above the fixed 8% floor.

If far fewer cells remain than expected, see troubleshooting. For multi-sample data, compute thresholds per sample; see troubleshooting.

MAD threshold QC (tested on this page)r
# MAD thresholds instead of the 200 / 2500 / 5% values of the PBMC3k tutorial
mad_out <- function(x, n, upper = FALSE) {
  m <- median(x); d <- mad(x)
  if (upper) x > m + n * d else x < m - n * d | x > m + n * d
}
bad <- mad_out(log1p(obj$nCount_RNA), 5) | mad_out(log1p(obj$nFeature_RNA), 5) |
       (mad_out(obj$percent.mt, 3, upper = TRUE) & obj$percent.mt > 8)
obj <- subset(obj, cells = colnames(obj)[!bad & obj$dbl_class == "singlet"])
  1. 01

    Look at the distributions

    Plot the UMI count, gene count and mitochondrial fraction to check for an obvious low-quality group.

  2. 02

    Compute the ranges

    For each metric, take the median plus or minus a multiple of MAD to get the kept range.

  3. 03

    Remove cells

    Remove cells outside the range. For the mitochondrial fraction, the cell must also be above 8%.

MetricSuggested ruleBasisNote
UMI count (nCount)Median ± 5 MAD on log1p valuessc-best-practices QC chapter5 MAD is a loose threshold, meant to avoid removing small clusters
Gene count (nFeature)Median ± 5 MAD on log1p valuesSame as aboveAn upper limit cannot replace doublet detection
Share of top-20 genesMedian ± 5 MADSame as aboveA high share means low library complexity (computed in the Scanpy route)
Mitochondrial fractionMedian + 3 MAD, and also above a fixed floorsc-best-practices uses 8%With 3 MAD alone, data with low mitochondrial content are over-filtered

Step 4

Why this stepNormalization removes differences in sequencing depth between cells. Dimension reduction compresses the variation of thousands of genes into a few principal components (PCs), and clustering is then done on them.

LogNormalize is the safe default: divide each cell's counts by its total UMIs, multiply by 10,000, then take the log. A 2023 comparison by Ahlmann-Eltze and Huber in Nature Methods found that this log transform plus PCA performs as well as or better than more complex methods such as SCTransform.

Highly variable genes are the genes that vary most across cells. This page uses 2,000; only these are scaled, and PCA is also run on them.

A principal component is a composite variable that combines the shared variation of many genes; PC1 explains the most variance. How many PCs to keep depends on the elbow; see the card below. To switch to SCTransform, see the branch on other tools.

Normalization, highly variable genes and PCA (tested on this page)r
obj <- NormalizeData(obj)                            # LogNormalize, scale.factor = 1e4
obj <- FindVariableFeatures(obj, nfeatures = 2000)
obj <- ScaleData(obj)                                # HVGs only by default
obj <- RunPCA(obj, npcs = 50)
ElbowPlot(obj, ndims = 50)

How to choose the number of PCs

Keep more PCs rather than fewer. On PBMC 3k, PC1 explains 2.9% of the variance. After the 7th PC, each PC explains only 0.18% to 0.24%, and the curve is nearly flat. The first 10, 30 and 50 PCs together explain 7.6%, 11.0% and 14.2%. The Seurat tutorial says 7 to 12 PCs are reasonable. For complex tissues or tens of thousands of cells, use 20 to 50. JackStraw is slow and is no longer a routine step in the official tutorial.

Step 5

Why this stepClustering groups similar cells together. The resolution sets how coarse the groups are. There is no single correct value, so compare several candidates and pick a stable one.

This page runs FindClusters at five resolutions from 0.2 to 1.0 at once, then uses clustree to plot how they relate. This page uses 0.6 as the example, which gives 9 clusters.

In a clustree plot, a cluster that receives arrows from two clusters in the layer above means the resolution is high enough to split cells again. On PBMC 3k, this crossing starts appearing between 0.4 and 0.6. The stability results across seeds are in the reference section on clustering.

The criteria are: the cluster structure stays stable across random seeds, and every cluster can be explained by markers. The lowest resolution that meets both criteria is usually the most suitable.

Clustering and clustree (tested on this page)r
obj <- FindNeighbors(obj, dims = 1:20)
obj <- FindClusters(obj, resolution = c(0.2, 0.4, 0.6, 0.8, 1.0))
obj <- RunUMAP(obj, dims = 1:20)

library(clustree)                                    # 先加载 clustree,见排错
clustree(obj, prefix = "RNA_snn_res.")

Step 6

Why this stepAnnotation gives each cluster a cell type name. You find the marker genes highly expressed in each cluster, then compare them with known markers of cell types.

FindAllMarkers finds marker genes cluster by cluster. A good marker has a high average log2 fold change (avg_log2FC), and a much higher fraction of cells expressing it in this cluster (pct.1) than in other clusters (pct.2).

In this page's B-cell cluster, CD79A is expressed in 0.936 of cells in the cluster and 0.041 in other clusters, which makes it a typical marker.

Automatic annotation tools can only return labels that exist in their reference data, so use them for cross-checking. If they conflict with markers, trust the markers and the tissue context. The CellTypist comparison is in the Scanpy branch, and other tools are compared in the other-tools branch.

Marker genes per cluster (tested on this page)r
Idents(obj) <- "RNA_snn_res.0.6"
markers <- FindAllMarkers(obj, only.pos = TRUE, min.pct = 0.25, logfc.threshold = 0.25)

Choose by your situation

Hand off to an agent

You can describe the analysis in one sentence, and the Scientify science agent will run it in a cloud workstation.

Example instruction: “Analyze the 6 10x samples in data/ (3 control, 3 treated). For each sample, run MAD-based QC and scDblFinder. First produce an unintegrated UMAP, then integrate with Harmony and scVI and compare. Choose the resolution with clustree and multi-seed ARI. Annotate with CellTypist and marker dot plots, and output the cell proportion of each cluster and the treated-vs-control differential genes in each cluster.”

The agent installs the remaining packages in a cloud workstation with Scanpy preinstalled. It completes QC and doublet detection per sample and records the cells removed at each step. After integration, clustering and annotation, it outputs the UMAP, clustree plot, marker dot plot, cell proportion table and differential gene table. When scVI needs a GPU, it is rented automatically for the task. The project keeps the scripts, parameters, logs and h5ad files, so the run can be reproduced.

You still need to check these yourself: whether the QC thresholds suit your tissue type; whether integration removed the biology you care about; whether the annotation matches the tissue and literature; and whether differential analysis treats samples, not cells, as replicates.

Branch: Scanpy

Both routes complete the same analysis. For more than 100,000 cells, or when you need deep-learning tools such as scVI, the Python route uses less memory. For R packages such as SingleR, CellChat or Monocle, choose Seurat.

The Python code below matches the main line step by step: loading, QC, doublets, normalization, clustering and markers. Thresholds and parameters are the same as in the Seurat version.

Annotation uses CellTypist. It needs a matrix that is log1p-transformed and normalized to 10,000 per cell, which is exactly the adata produced above.

For converting between Seurat and Scanpy, anndataR is recommended. The SeuratDisk repository has had no new commits since November 2023; conversion problems are in troubleshooting.

Full Scanpy workflow (tested and passing on this page)python
# Scanpy 1.12 (Python >= 3.12): PBMC 3k from Cell Ranger output to annotated clusters
import numpy as np, scanpy as sc
from scipy.stats import median_abs_deviation

adata = sc.read_10x_mtx("filtered_gene_bc_matrices/hg19", var_names="gene_symbols")
# Cell Ranger >= 3: sc.read_10x_h5("filtered_feature_bc_matrix.h5")
adata.var_names_make_unique()

# QC metrics: mitochondrial / ribosomal / hemoglobin genes (mouse: "mt-", ("Rps","Rpl"), "^Hb[^(p)]")
adata.var["mt"] = adata.var_names.str.startswith("MT-")
adata.var["ribo"] = adata.var_names.str.startswith(("RPS", "RPL"))
adata.var["hb"] = adata.var_names.str.contains("^HB[^(P)]")
sc.pp.calculate_qc_metrics(adata, qc_vars=["mt", "ribo", "hb"], percent_top=[20], log1p=True, inplace=True)

# Doublets on raw counts, per capture (batch_key="sample" when several samples are concatenated)
sc.pp.scrublet(adata, random_state=0)

# MAD outliers: 5 MAD on counts / genes / top-20 share, mito 3 MAD AND above a fixed floor
def outlier(x, nmads, upper_only=False):
    med, mad = np.median(x), median_abs_deviation(x)
    return (x > med + nmads * mad) if upper_only else ((x < med - nmads * mad) | (x > med + nmads * mad))
o = adata.obs
bad = (outlier(o.log1p_total_counts, 5) | outlier(o.log1p_n_genes_by_counts, 5)
       | outlier(o.pct_counts_in_top_20_genes, 5)
       | (outlier(o.pct_counts_mt, 3, upper_only=True) & (o.pct_counts_mt > 8)))
adata = adata[~bad & ~adata.obs.predicted_doublet].copy()
sc.pp.filter_genes(adata, min_cells=3)

# Normalize, HVG, PCA
adata.layers["counts"] = adata.X.copy()
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, n_top_genes=2000, flavor="seurat_v3", layer="counts")  # add batch_key="sample" for multi-sample data
adata.raw = adata                                     # keep all genes (log-normalized) for markers and plots
hv = adata[:, adata.var.highly_variable].copy()       # scale only HVGs; scaling all genes makes X dense
sc.pp.scale(hv, max_value=10)
sc.tl.pca(hv, n_comps=50)

# Graph, clustering, UMAP
sc.pp.neighbors(hv, n_neighbors=15, n_pcs=30)
for r in (0.2, 0.4, 0.6, 0.8, 1.0):
    sc.tl.leiden(hv, resolution=r, flavor="igraph", n_iterations=2, key_added=f"leiden_{r}")
sc.tl.umap(hv)

# Markers on log-normalized expression of all genes
adata.obs["leiden"] = hv.obs["leiden_0.6"].values
sc.tl.rank_genes_groups(adata, "leiden", method="wilcoxon", use_raw=False)
sc.pl.rank_genes_groups_dotplot(adata, n_genes=5)
CellTypist annotation (tested and passing on this page)python
# CellTypist on log1p data normalized to 10,000 counts per cell (adata after normalize_total + log1p)
import celltypist
from celltypist import models
models.download_models(model=["Immune_All_Low.pkl"])
pred = celltypist.annotate(adata, model="Immune_All_Low.pkl",
                           majority_voting=True, over_clustering=adata.obs["leiden"])
adata.obs["celltypist"] = pred.predicted_labels["majority_voting"]
adata.obs["celltypist_conf"] = pred.probability_matrix.max(axis=1)   # low values = label not in the model
Convert between h5ad and Seuratr
# R: anndataR 1.2 (Bioconductor). rhdf5 is a separate install, otherwise:
#   Error: HDF5AnnData requires the rhdf5 package
# BiocManager::install(c("anndataR", "rhdf5"))
library(Seurat); library(anndataR)

obj <- read_h5ad("pbmc3k_processed.h5ad", as = "Seurat")   # h5ad -> Seurat: X and layers become layers, obsm -> reductions
obj <- JoinLayers(obj)                                       # split layers are skipped with a warning only
write_h5ad(obj, "from_seurat.h5ad")                          # Seurat -> h5ad: layers "counts" and "data", X left empty

# Python: X is empty after the Seurat -> h5ad direction, point it at a layer
import anndata as ad
adata = ad.read_h5ad("from_seurat.h5ad")
adata.X = adata.layers["counts"].copy()                      # or layers["data"] for log-normalized values
StepSeurat v5 (R)Scanpy 1.12 (Python)
Read inRead10X / Read10X_h5sc.read_10x_mtx / sc.read_10x_h5
QC metricsPercentageFeatureSet(pattern = "^MT-")sc.pp.calculate_qc_metrics(qc_vars=["mt"])
DoubletsscDblFinder, DoubletFindersc.pp.scrublet
NormalizationNormalizeData / SCTransformsc.pp.normalize_total + sc.pp.log1p
Highly variable genesFindVariableFeatures(nfeatures = 2000)sc.pp.highly_variable_genes(n_top_genes=2000)
IntegrationIntegrateLayers (CCA, RPCA, Harmony, FastMNN, scVI)harmonypy, scVI, Scanorama
ClusteringFindNeighbors + FindClusters (Louvain by default)sc.pp.neighbors + sc.tl.leiden
MarkersFindAllMarkerssc.tl.rank_genes_groups
Automatic annotationSingleR, AzimuthCellTypist
Large dataBPCells on disk + SketchDataread_lazy, backed mode, Dask
Storage.rds / .qs.h5ad / .zarr

Branch: multiple samples

Start without integration by coloring the UMAP by sample. If the same cell types from different samples already mix together, you do not need integration.

Integration only changes the dimension-reduction coordinates (such as harmony or integrated.rpca); the expression matrix stays the same. Differential analysis always uses the RNA counts and data layers.

Split by sample before integrating, and run JoinLayers before differential analysis. Causes of errors in these two steps are in troubleshooting.

Seurat v5: split, integrate, JoinLayers and re-integrate a subset (tested on this page)r
# Seurat v5 multi-sample integration: split -> per-layer preprocessing -> IntegrateLayers -> JoinLayers
obj <- merge(s1, y = list(s2, s3), add.cell.ids = c("s1", "s2", "s3"))   # already one layer per object: counts.1, counts.2, counts.3
# Object built from one matrix, or after JoinLayers: split by sample first
# obj[["RNA"]] <- split(obj[["RNA"]], f = obj$sample)
# Splitting a merged object again fails: The following layers are already split: 'counts.1', 'counts.2' Please join before splitting
obj <- NormalizeData(obj); obj <- FindVariableFeatures(obj); obj <- ScaleData(obj); obj <- RunPCA(obj)

# Unintegrated baseline first
obj <- FindNeighbors(obj, dims = 1:30, reduction = "pca")
obj <- FindClusters(obj, resolution = 0.5, cluster.name = "unintegrated_clusters")
obj <- RunUMAP(obj, dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")

obj <- IntegrateLayers(obj, method = HarmonyIntegration, orig.reduction = "pca", new.reduction = "harmony")
# alternatives: method = RPCAIntegration (more conservative), CCAIntegration, FastMNNIntegration, scVIIntegration
obj <- FindNeighbors(obj, reduction = "harmony", dims = 1:30)
obj <- FindClusters(obj, resolution = 0.5, cluster.name = "harmony_clusters")
obj <- RunUMAP(obj, reduction = "harmony", dims = 1:30, reduction.name = "umap.harmony")

obj <- JoinLayers(obj)          # before FindMarkers / FindAllMarkers / GetAssayData

# Re-clustering a subset: layers are joined now, so split again before IntegrateLayers
sub <- subset(obj, idents = c("0", "3"))
sub[["RNA"]] <- split(sub[["RNA"]], f = sub$sample)
sub <- NormalizeData(sub); sub <- FindVariableFeatures(sub); sub <- ScaleData(sub); sub <- RunPCA(sub)
sub <- IntegrateLayers(sub, method = HarmonyIntegration, orig.reduction = "pca", new.reduction = "harmony_sub")
sub <- FindNeighbors(sub, reduction = "harmony_sub", dims = 1:20); sub <- FindClusters(sub, resolution = 0.3)
sub <- JoinLayers(sub)
Scanpy: Harmony and scVIpython
# Scanpy: Harmony (harmonypy) and scVI on the same AnnData
import scanpy as sc
sc.pp.highly_variable_genes(adata, n_top_genes=2000, flavor="seurat_v3", layer="counts", batch_key="sample")
hv = adata[:, adata.var.highly_variable].copy()
sc.pp.scale(hv, max_value=10); sc.tl.pca(hv, n_comps=50)
# sc.external.pp.harmony_integrate(hv, key="sample") fails with harmonypy 2.x:
#   ValueError: Value passed for key 'X_pca_harmony' is of incorrect shape ... (50,) while it should have had (n_cells,)
# harmonypy 2.x already returns Z_corr as cells x PCs, the Scanpy 1.12.4 wrapper transposes it again
import harmonypy
ho = harmonypy.run_harmony(hv.obsm["X_pca"], hv.obs, "sample")
Z = ho.Z_corr
hv.obsm["X_pca_harmony"] = Z if Z.shape[0] == hv.n_obs else Z.T
sc.pp.neighbors(hv, use_rep="X_pca_harmony", n_pcs=30)
sc.tl.leiden(hv, resolution=0.5, flavor="igraph", n_iterations=2)

# scVI: needs raw counts; a GPU shortens training, CPU works for tens of thousands of cells
import scvi
scvi.model.SCVI.setup_anndata(hv, layer="counts", batch_key="sample")
m = scvi.model.SCVI(hv, n_latent=30)
m.train()                                                      # max_epochs scales down automatically for large data
hv.obsm["X_scVI"] = m.get_latent_representation()
sc.pp.neighbors(hv, use_rep="X_scVI")

How to check for over-integration

Cluster before and after integration and check three things: whether each cluster's markers still belong to one lineage; whether cell states expected only in one condition still form their own clusters; and whether each sample's share in each cluster has been flattened to the same value. The Seurat tutorial recommends comparing several integration methods with the unintegrated result.

Use the RNA assay after JoinLayers for differential analysis after integration

In v4, IntegrateData creates an integrated assay whose values are corrected low-dimensional reconstructions, which are not suitable for testing expression differences. In v5, IntegrateLayers only creates a reduction, and differential analysis is done on the RNA assay after JoinLayers.

After extracting a subset, re-select highly variable genes

After subsetting a large group such as T cells, rerun FindVariableFeatures, ScaleData and RunPCA before clustering. If you reuse the highly variable genes and PCs from all cells, the genes that separate subtypes may be missing. For multi-sample data, split and integrate again by sample; see the code below.

ScenarioFirst choiceAlternativeConsequence of a wrong choice
A few samples from the same experiment and platform, with weak batch effectsNo integration, or HarmonyRPCAForcing CCA may erase real compositional differences between samples
Control vs. treated (disease vs. normal), where condition-specific cell states are expectedHarmony or RPCA (Seurat calls RPCA more conservative)scVIOver-integration merges states specific to the treated group into control clusters, so later differential analysis finds no signal
Several labs, platforms or atlas-scale data, with many batches and large compositional differencesscVI; scANVI if some cells have labelsScanoramaHarmony under-corrects, so one cell type splits into several clusters by source
Hundreds of thousands of cells or moreHarmony (fast, low memory) or scVI (GPU)Seurat sketch, then integrateCCA has high memory and time costs on large data
Luecken et al. 2022 (Nature Methods) benchmarked 13 integration tasks, 68 method and preprocessing combinations, and more than 1.2 million cells. scANVI, Scanorama, scVI and scGen performed well on complex tasks; linear methods such as Harmony performed well on simple batch tasks.

Branch: other tools

The main line uses scDblFinder, LogNormalize and marker genes. The table lists alternatives and when each one fits.

Ambient RNA is free RNA floating in the droplet, released from broken cells. You can skip correction if you only do clustering and rough annotation. If you do differential expression, or report that a gene is specific to a cluster, correction is recommended.

Janssen et al. 2023 (Genome Biology) compared CellBender, DecontX and SoupX. Background removal gave little improvement for clustering and cell classification, the largest improvement was for marker gene detection, and CellBender gave the most accurate estimate of background level.

Measured on this page: the core workflow (LogNormalize to UMAP) took 15.9 seconds; SCTransform v2 took 106.7 seconds without glmGamPoi installed, and its clustering had an ARI of 0.73 against the LogNormalize clustering.

Annotate clusters with SingleR (not run on this machine)r
# SingleR + celldex (Bioconductor). On macOS arm64 bioconda has no SingleR build:
# install with BiocManager::install(c("SingleR", "celldex")) inside the R environment
library(SingleR); library(celldex)
ref <- celldex::MonacoImmuneData()                    # immune; HumanPrimaryCellAtlasData() for broad tissue types
pred <- SingleR(test = LayerData(obj, layer = "data"), ref = ref,
                labels = ref$label.fine, clusters = obj$seurat_clusters)   # per-cluster mode
obj$singler <- pred$pruned.labels[match(obj$seurat_clusters, rownames(pred))]
plotScoreHeatmap(pred)                                # check that the best score clearly beats the second
ProblemToolWhen it fitsNote
DoubletsDoubletFinder (R)You prefer Seurat and a single-sample objectDo not run it on a merged or integrated object
DoubletsScrublet (built into Scanpy)Python routeThe automatic threshold is conservative, so check the score histogram; on PBMC 3k this page flags 32 cells (1.2%)
Ambient RNASoupX (R)High-expression genes such as hemoglobin or immunoglobulin appear in cell groups where they should notNeeds the raw and filtered matrices and a rough clustering
Ambient RNACellBender (Python)Marker and differential analyses need to be accurateOfficial guidance is to use a GPU (--cuda); parameters are estimated automatically since v0.3.0
NormalizationSCTransform v2Large differences in sequencing depth, and you want to skip ScaleDataRun separately for each sample when integrating; differential analysis issues are in troubleshooting
NormalizationPearson residuals (Scanpy)You want to replace the log transformOn this page at res 0.6 it gives 10 clusters; ARI with the log workflow is 0.63
AnnotationSingleR + celldex (R)R route, and the reference contains the relevant cell typesReferences are mostly bulk data from purified cells and lack tissue-specific subtypes and disease states
AnnotationCellTypist (Python)Python route, mainly immune tissuesModels are mainly for immune cells; choose an organ-specific model for non-immune tissue
AnnotationAzimuth (R / web)Tissues already covered by its reference atlases (PBMC, lung, kidney, bone marrow and others)Only covers tissues that have a reference; the reference loads from the internet by default

Branch: large data

The biggest memory cost in single-cell analysis is dense matrices. Count matrices are sparse, but once ScaleData or sc.pp.scale runs on all genes, it creates a dense cells × genes matrix.

Measured on this page: after filtering, the sparse matrix of PBMC 3k takes 16.8 MB. Converted to dense (2,607 × 13,607 × 8 bytes), it takes 270.6 MB, 16 times larger. At this ratio, 100,000 cells × 20,000 genes scaled over all genes needs about 16 GB for this matrix alone.

Estimated memory by cell count is in the table below.

Large dataset: BPCells + sketch (R) and read_lazy (Python)r
# Seurat v5 + BPCells: counts stay on disk, analyze a 50,000-cell sketch, project back
library(Seurat); library(BPCells)
options(future.globals.maxSize = 4e9)
mat <- open_matrix_10x_hdf5("filtered_feature_bc_matrix.h5")
write_matrix_dir(mat, dir = "bpcells_counts")              # one-time conversion to the on-disk format
obj <- CreateSeuratObject(open_matrix_dir("bpcells_counts"))
obj <- NormalizeData(obj); obj <- FindVariableFeatures(obj)
obj <- SketchData(obj, ncells = 50000, method = "LeverageScore", sketched.assay = "sketch")
DefaultAssay(obj) <- "sketch"
obj <- FindVariableFeatures(obj); obj <- ScaleData(obj); obj <- RunPCA(obj)
obj <- FindNeighbors(obj, dims = 1:50); obj <- FindClusters(obj, resolution = 1)
obj <- RunUMAP(obj, dims = 1:50, return.model = TRUE)
obj <- ProjectData(obj, assay = "RNA", full.reduction = "pca.full", sketched.assay = "sketch",
                   sketched.reduction = "pca", umap.model = "umap", dims = 1:50,
                   refdata = list(cluster_full = "seurat_clusters"))

# Python side: open .h5ad without loading X (anndata >= 0.12)
import anndata as ad
a = ad.experimental.read_lazy("big.h5ad")   # lazy obs/var/X; subset first, then .to_memory()
a = ad.read_h5ad("big.h5ad", backed="r")    # older backed mode: read-only X on disk
  1. 01

    Scale only highly variable genes

    This is Seurat's default. Do not pass features = rownames(obj).

  2. 02

    Release matrices you no longer need

    Before saving, delete scale.data and the SCT assay if you no longer need them.

  3. 03

    Analyze a sample

    In Seurat, keep counts on disk with BPCells, analyze a 50,000-cell sketch with SketchData, then project the results back to all cells with ProjectData.

  4. 04

    Load lazily

    In Python, use anndata's read_lazy or backed mode, and read only the subset you need into memory.

ScaleMemory (measured or reported)SourceSuggested setup
2,600 cells (PBMC 3k)Scanpy full workflow peak 0.98 GB; Seurat full workflow (including SCTransform and integration tests) peak 3.86 GB, Seurat object 100 MBMeasured on this pageA laptop is enough
27,000 cells (PBMC 3k copied 10 times)Scanpy scaling only highly variable genes peak 2.64 GB; scaling all 13,607 genes peak 4.03 GBMeasured on this page (copied cells used only for memory tests)16 GB RAM
81,000 cells (copied 30 times)Scanpy scaling only highly variable genes peak 4.42 GBMeasured on this page32 GB RAM
300,000 cells, basic workflowSeurat about 40 GB, Scanpy about 10 GBBiomamba (CSDN), measured64–128 GB, or switch to Scanpy or BPCells
1.3 million cells (BPCells on disk)Seurat object about 596 MB, analyzed on a 50,000-cell sampleSeurat sketch official tutorialDepends on the sample size; 32–64 GB is workable

Concepts and judgment

Judgement

The judgements below have no single standard. The reasons are listed so you can explain your choices in a paper.

Why the mitochondrial threshold needs a fixed floor

With 3 MAD alone, the mitochondrial upper limit on PBMC 3k is only 3.65%, and 276 cells are removed. With the 8% floor added, only 104 cells are removed. Most of the extra cells are normal PBMCs with mitochondrial fractions between 3.7% and 5%.

Literature on mitochondrial thresholds

Osorio and Cai 2021 analyzed 1,349 datasets and 5.53 million cells from PanglaoDB. Among 121 mouse tissues, only whole kidney, whole heart and distal small intestine have an average mitochondrial fraction above 5%; among 44 human tissues, 13 have averages above 5%. That is why 10% is often used for human data and 5% for mouse.

Mitochondrial thresholds for single-nucleus data

Nuclei have no mitochondria, so mitochondrial reads come from cytoplasmic contamination. The mitochondrial fraction in single-nucleus data is usually far below that of single-cell data, so 1%–5% can serve as the upper limit. A nuclear cluster with high mitochondrial content may be contamination rather than low-quality cells.

Why low-RNA cells can be removed by mistake

On PBMC 3k, there are 19 platelet-like cells with high PPBP expression, and their median gene count is only 397. MAD-based QC removes 10 of them, and the remaining 9 are too few to form their own cluster. The fixed-threshold workflow keeps this group of 13 cells. If platelets, erythroid precursors or other low-RNA cells matter to you, check the markers of removed cells first.

When to remove whole clusters of doublets

Labeled cells do not have to be deleted immediately. After clustering, if a small cluster highly expresses markers of two lineages at once (for example CD3E and CD14) and has high doublet scores, remove the whole cluster. sc-best-practices also keeps flagged cells at first. The code on this page deletes them directly to keep the workflow short.

A cluster where ribosomal genes rank first

In the Scanpy results, the top 5 markers of the large T-cell cluster are LDHB and 4 RPS genes. High ribosomal gene expression is one feature of naive T cells, so it cannot be used alone for annotation; check with CD3E, IL7R and CCR7.

Clustering stability measured by ARI

ARI (adjusted Rand index) measures how consistent two clusterings are; it ranges from 0 to 1, and closer to 1 means more stable. On PBMC 3k with 30 PCs at res 0.4, the 5 random seeds agree almost completely (ARI 0.99).

Use samples, not cells, as replicates in differential analysis

For group comparisons, the replicate unit should be the sample, not the cell. If you compute with cells, cells from the same sample are not independent replicates, so the conclusions are easily overconfident.

Reference and appendix

Reference

On PBMC 3k at res 1.5, the cluster count across seeds ranged from 16 to 18, and ARI dropped to 0.75, so the extra clusters are unstable.

At the same resolution, 10 PCs split 1 to 3 more clusters than 30 PCs, so report the PC count together with the resolution. The official Seurat guidance is that around 3,000 cells a resolution of 0.4 to 1.2 works, and more cells need higher resolutions.

Settingres 0.2res 0.4res 0.6res 0.8res 1.0res 1.5
Seurat, dims 1:10 (Louvain)7910111113
Scanpy, 10 PCs (Leiden, 5 seeds)6 (ARI 0.96)8–9 (0.85)9–10 (0.89)11–12 (0.83)12–13 (0.85)16–18 (0.75)
Scanpy, 30 PCs (Leiden, 5 seeds)5 (0.95)7 (0.99)8 (0.86)9 (0.90)9 (0.89)12–14 (0.75)
Measured on this page, PBMC 3k. Values in parentheses are the average pairwise ARI across 5 random seeds; closer to 1 means more stable. Seurat and Scanpy give different cluster counts because their graph construction and clustering algorithms differ.

Measured on this page

Test environment: macOS arm64 (8 cores, 16 GB), Scanpy 1.12.4, anndata 0.13.4, Python 3.12, Seurat 5.5.1, SeuratObject 5.4.0, R 4.5, with 10x PBMC 3k (2,700 cells). Other tasks were running on the same machine during the tests, so timings only show the order of magnitude.

ItemScanpySeurat
Load2,700 cells × 32,738 genesAfter CreateSeuratObject(min.cells = 3, min.features = 200): 2,700 cells × 13,714 genes
QCFixed thresholds keep 2,638; MAD keeps 2,596Fixed thresholds keep 2,638
DoubletsScrublet 32 (1.2%)scDblFinder 124 (4.6%)
Entering clustering2,607 cells × 13,607 genes (fixed thresholds + Scrublet doublets removed)2,638 cells
Code block on this page (MAD + doublets removed)2,567 cells, 30 PCs, res 0.6: 7 clusters (no platelet cluster)2,564 cells, dims 1:20, res 0.6: 9 clusters
Clustering30 PCs, Leiden res 0.6: 8 clustersdims 1:10, res 0.5: 9 clusters
AnnotationCellTypist majority-vote labels agree with markers (8 of 8 clusters)FindAllMarkers 11.5 seconds (presto not installed)
TimeFull script 186 seconds, of which Scrublet and QC 114 seconds (including the first numba compilation)Core workflow 15.9 seconds; SCTransform v2 106.7 seconds
Peak memory0.98 GB3.86 GB (including SCTransform and integration tests)
  • Errors reproduced on Seurat 5.5.1: GetAssayData(slot = ) no longer works; @counts does not exist; GetAssayData and FindMarkers fail with multiple layers; unsplit IntegrateLayers fails with attempt to set an attribute on NULL. All are in troubleshooting.
  • On Seurat 5.5.1, RunUMAP uses R's uwot by default (cosine distance), so the result is not exactly the same as older tutorials that call Python umap-learn through reticulate.
  • SingleR was not run on this machine: bioconda on macOS arm64 has no bioconductor-singler package, so only the function and parameter names were checked.
  • CellBender and scVI need a GPU or long CPU time, and BPCells was not installed on this machine. Only the parameter names and documentation were checked for these parts.
  • The anndataR 1.2.2 round trip was run: rhdf5 must be installed separately, and an h5ad written without JoinLayers has no expression matrix.

Experience from China

The items below come from CSDN and Zhihu columns. Only items with the original error text or the author's measurements, and consistent with the official documentation or the measurements on this page, are included.

Re-integrating a subset fails with “NULL是不能有属性的”

At least two CSDN authors (July and August 2024) recorded the same error. One met it after extracting an immune subset and integrating with Harmony. The cause is that the layers were already merged. The fix is to split first; see Seurat GitHub Discussion #9045. This page reproduced the error on Seurat 5.5.1 and checked the fix.

A few samples do not always need batch correction

One CSDN author compared no integration, SCTransform and Harmony on 4 mouse prefrontal samples. Without integration the samples already mixed well, and the conclusion was to look at the data before deciding. This agrees with the Seurat recommendation to compare with the unintegrated result first.

Measured memory for 300,000 cells

Biomamba (CSDN, December 2024) tested a basic workflow (normalization to UMAP) on 25,000 to 300,000 cells. At 300,000 cells, Seurat needed about 40 GB and Scanpy about 10 GB. The same article notes that monocle2 pseudotime on 50,000 cells can peak above 300 GB. The author runs a server rental business, but the numbers are backed by a measurement script and can serve as an order-of-magnitude reference.

Memory saved by sparse matrices

The Zhihu column “Single-cell analysis | Seurat basic workflow | step-by-step tutorial” measured 709.6 MB for the dense and 29.9 MB for the sparse PBMC 3k raw matrix, a 23.7-fold difference. This page measured 16 times on the filtered matrix. Both show that the memory problem mainly comes from the step that makes the matrix dense.

Troubleshooting

Error messages and pitfalls from old tutorials are collected here. Find your error message or symptom.

GetAssayData(obj, slot = "counts") fails with The `slot` argument of `GetAssayData()` was deprecated in SeuratObject 5.0.0 and is now defunct. Or obj@assays$RNA@counts fails with no slot of name "counts".

Cause: Seurat v5's Assay5 stores matrices as layers (counts, data, scale.data). Since SeuratObject 5.0 the slot argument is deprecated, and the @counts syntax fails directly on 5.4. Copying v4 tutorial code fails here.

Fix: Change slot = to layer =. Change obj@assays$RNA@counts to obj[["RNA"]]$counts or LayerData(obj, layer = "counts"). The code is below.

# Seurat v5 / SeuratObject 5.4: replacements for v4 code
GetAssayData(obj, slot = "counts")   # Error: The `slot` argument of `GetAssayData()` was deprecated in SeuratObject 5.0.0 and is now defunct.
obj@assays$RNA@counts                # Error: no slot of name "counts" for this object of class "Assay5"

obj[["RNA"]]$counts                  # v5 accessors
LayerData(obj, assay = "RNA", layer = "data")
GetAssayData(obj, layer = "data")    # works only while the assay has one "data" layer

# Old v4 object read into v5: convert the assay class when a tool needs Assay5 (e.g. BPCells, IntegrateLayers)
obj[["RNA"]] <- as(obj[["RNA"]], "Assay5")
# Tool that only accepts v4 assays: convert back (merge layers first)
obj <- JoinLayers(obj); obj[["RNA"]] <- as(obj[["RNA"]], "Assay")
IntegrateLayers fails with attempt to set an attribute on NULL (in a Chinese locale: “NULL是不能有属性的”). With CCAIntegration it fails with no applicable method for 'Assays' applied to an object of class "NULL".

Cause: Integration was run without splitting by sample, or the layers were already merged when integrating a subset again. On Seurat 5.5.1 this page reproduced it: running Harmony without split fails with attempt to set an attribute on NULL, and integrating a subset after subsetting fails with the same error.

Fix: Split by sample before integrating. Before integrating a subset again, split the subset by sample as well.

obj[["RNA"]] <- split(obj[["RNA"]], f = obj$sample)   # split by sample before IntegrateLayers
GetAssayData fails with GetAssayData doesn't work for multiple layers in v5 assay. FindMarkers fails with data layers are not joined. Please run JoinLayers.

Cause: After merging multiple samples, each original object keeps its own layer (for example counts.1 and counts.2), so the RNA assay has several layers, and single-layer functions cannot read them directly.

Fix: Run obj <- JoinLayers(obj) first, then access the matrix or run FindMarkers or FindAllMarkers.

Splitting an object that is already split by sample fails with The following layers are already split: 'counts.1', 'counts.2' Please join before splitting.

Cause: split only works on merged layers. Once an object is split by sample, it cannot be split again.

Fix: Run obj <- JoinLayers(obj) first, then split by sample.

After QC, far fewer cells remain than expected, and most removed cells have more than 2,500 detected genes.

Cause: The nFeature < 2500 cutoff from the PBMC 3k tutorial was copied. From Cell Ranger 7.0, --include-introns in count defaults to true, so intron reads are counted and gene numbers go up overall. The PBMC 3k cutoff came from data made with Cell Ranger 1.1 in 2016 (median genes on this page: 817).

Fix: Compute thresholds from the distribution of your own data. This page uses MAD; see step 3.

In multi-sample data, many normal cells from low-depth samples are removed.

Cause: MAD was computed once after merging samples. High-depth samples shift the distribution, so normal cells in low-depth samples are flagged as outliers.

Fix: Compute the MAD ranges separately for each sample, then apply them to that sample.

After QC there is no platelet cluster, and the cells with high PPBP expression have disappeared.

Cause: Platelets have low RNA content (median gene count 397 on PBMC 3k), so MAD-based QC removes part of them. The reason is in the judgement section.

Fix: Compare the markers of the removed cells. If low-RNA cells matter to you, use fixed thresholds or loosen the floor. On this page, the fixed-threshold workflow kept a group of 13 cells.

SCTransform prints could not find glmGamPoi installed and runs noticeably slower.

Cause: Without glmGamPoi, SCTransform falls back to a slow implementation. On this page, 2,638 cells took 106.7 seconds; the gap grows with tens of thousands of cells.

Fix: Run BiocManager::install("glmGamPoi").

After SCTransform on multiple samples, direct FindMarkers results depend on the sequencing depth of each sample.

Cause: SCT residuals are only used for dimension reduction and clustering. Differential analysis without correcting for each sample's sequencing depth is not valid.

Fix: Run PrepSCTFindMarkers first to correct for depth per sample. Or switch back to the RNA assay and use the LogNormalize data layer for differential analysis.

The clustree plot fails with Unknown guide: edge_colourbar when saved with ggsave or printed.

Cause: When clustree::clustree() is called without loading the package, ggraph, which the plot needs, is not loaded. (Tested on this page with clustree 0.5.1, ggraph 2.2.2 and ggplot2 4.0.3.)

Fix: Run library(clustree) first, then draw the plot.

sc.tl.louvain fails with ModuleNotFoundError. Or sc.tl.leiden prints a FutureWarning: The `igraph` implementation of leiden clustering is *orders of magnitude faster*.

Cause: In Scanpy 1.12, louvain is deprecated, and the environment has no louvain package. Leiden without a flavor still uses leidenalg.

Fix: Use sc.tl.leiden(adata, flavor="igraph", n_iterations=2), which matches the code on this page.

sc.external.pp.harmony_integrate fails with ValueError: Value passed for key 'X_pca_harmony' is of incorrect shape.

Cause: harmonypy 2.x returns Z_corr already as cells × PCs, and the Scanpy 1.12.4 wrapper transposes it again. (Measured with harmonypy 2.0.2.)

Fix: Skip the wrapper and call harmonypy directly, then write X_pca_harmony according to the shape.

import harmonypy
ho = harmonypy.run_harmony(hv.obsm["X_pca"], hv.obs, "sample")
Z = ho.Z_corr
hv.obsm["X_pca_harmony"] = Z if Z.shape[0] == hv.n_obs else Z.T
pip install scanpy 1.12 fails because the current environment's Python is older than 3.12.

Cause: Scanpy 1.12.0 requires Python 3.12 or later.

Fix: Switch to an environment with Python 3.12 or later and install again.

Installing bioconductor-singler from bioconda fails on macOS arm64.

Cause: bioconda has no SingleR package for this platform.

Fix: In R, run BiocManager::install(c("SingleR", "celldex")).

FindAllMarkers runs very slowly and prints a message asking you to install presto.

Cause: Without presto, Seurat uses its R implementation of the Wilcoxon test, which is slower.

Fix: Install presto. From Seurat 5.6.0, FindAllMarkers can compare all clusters in one presto call.

read_h5ad or write_h5ad in anndataR fails with Error: HDF5AnnData requires the rhdf5 package.

Cause: rhdf5 is not installed automatically with anndataR and must be installed separately.

Fix: Run BiocManager::install(c("anndataR", "rhdf5")).

Writing a Seurat object without JoinLayers to h5ad only prints the warning Skipping Layer "counts.A" with unexpected dimensions, and the file has no expression matrix.

Cause: The object still has a multi-layer structure, so the expression matrices of the layers are skipped when writing.

Fix: Run JoinLayers before writing. After writing, X is empty, so in Python set adata.X to one of the layers manually.

R reports vector memory limit of 16.0 Gb reached.

Cause: R's default memory limit is 16 GB, and the object exceeds it.

Fix: On macOS, set R_MAX_VSIZE=32Gb in ~/.Renviron, and adjust the value to your machine's memory.

Seurat reports a future.globals.maxSize limit error when running with multiple workers.

Cause: The large object exceeds the default global variable limit of the future package.

Fix: Run options(future.globals.maxSize = 4e9), or set a larger value.

Some genes cannot be found when matching names against an external marker table or GTF annotation. Creating the object also prints the warning Feature names cannot have underscores.

Cause: CreateSeuratObject replaces underscores in gene names with dashes.

Fix: Apply the same replacement to the external list before matching, so that underscores become dashes in both.

Sources

FAQ

What mitochondrial threshold should I use?

There is no universal value. For each sample compute the median plus 3 MAD of the mitochondrial fraction and combine it with a fixed floor, taking the more lenient of the two: 10% is common for human tissue and 5% for mouse (Osorio and Cai 2021), and Single-cell Best Practices uses 8%. For cell types with naturally high mitochondrial content such as cardiomyocytes or renal tubules, judge together with UMI counts and the clustering; for single-nucleus data the cap is usually 1%–5%.

Seurat v4 code fails on v5. What should I change?

Replace slot = with layer =, and obj@assays$RNA@counts with obj[["RNA"]]$counts or LayerData(). Run JoinLayers on multi-sample objects before GetAssayData and FindMarkers, and split by sample before IntegrateLayers. The v4 integration workflow of SplitObject plus IntegrateData becomes split plus IntegrateLayers.

How do I choose the clustering resolution?

Scan a range (for example 0.2 to 1.5), use clustree to see at which resolution a cluster starts receiving arrows from several parent clusters, and compare results across random seeds with ARI. Pick the lowest stable resolution at which every cluster has clear markers; for subtypes, recluster large clusters on their own. On PBMC 3k in this page the stable range is 0.4–0.6.

How does Harmony relate to Seurat's IntegrateLayers?

IntegrateLayers is the unified interface of Seurat v5; with method = HarmonyIntegration it calls the harmony package. You can also call RunHarmony(obj, group.by.vars = "sample") directly. Both only create a new embedding and leave the expression matrix unchanged.

How much server memory does single-cell analysis need?

Estimate from the number of cells. Up to 10,000 cells a 16 GB laptop is enough; for 50,000 to 100,000 cells 64 GB is advisable; at 300,000 cells the basic workflow takes about 40 GB in Seurat and about 10 GB in Scanpy; for larger datasets use BPCells with sketching or lazy reading in Scanpy. Downstream analyses such as pseudotime or cell communication can need far more memory than the basic workflow.

How do I convert a Seurat object to h5ad?

Install anndataR and rhdf5, run JoinLayers, then write_h5ad(obj, "out.h5ad"); the written file keeps expression in layers["counts"] and layers["data"] with X empty, so set adata.X after reading it in Python. For the other direction use read_h5ad("x.h5ad", as = "Seurat"). SeuratDisk has had no commits since November 2023.

Hand your single-cell analysis to Scientify

The research agent runs this workflow in an isolated cloud computer with Scanpy preinstalled: per-sample QC and doublet detection, comparison of integration methods, resolution selection, annotation and differential analysis. It rents a GPU when needed and keeps every script, parameter and log. New users get $5 of free credit.