Seurat
A Seurat object holds the counts, the normalized values, the cell metadata, the
reductions and the neighbor graph of one single-cell experiment. Every example runs on
PBMC 3k, 2,700 peripheral blood mononuclear cells from a healthy donor that 10x Genomics
published as a public dataset, processed with Cell Ranger 1.1.0. The filtered matrix
ships in the image at /opt/data/pbmc3k. The code uses the Seurat 5 API. Where an older
tutorial uses a Seurat 4 call, the page names it.
Quick reference
Section titled “Quick reference”| Task | Seurat 5 call |
|---|---|
| Read a 10x directory | Read10X(data.dir = "...") |
| Create the object | CreateSeuratObject(counts, min.cells = 3, min.features = 200) |
| Mitochondrial share | PercentageFeatureSet(obj, pattern = "^MT-") |
| Metadata | obj[[]] |
| Filter cells | subset(obj, subset = nFeature_RNA > 200 & percent.mt < 5) |
| Normalize | NormalizeData(obj) |
| Variable genes | FindVariableFeatures(obj, nfeatures = 2000) |
| Scale | ScaleData(obj) |
| PCA | RunPCA(obj) and ElbowPlot(obj) |
| Graph and clusters | FindNeighbors(obj, dims = 1:10) and FindClusters(obj, random.seed = 42) |
| UMAP | RunUMAP(obj, dims = 1:10, seed.use = 42) |
| Markers per cluster | FindAllMarkers(obj, only.pos = TRUE) |
| Two groups | FindMarkers(obj, ident.1, ident.2) |
| Plots | VlnPlot(), FeaturePlot(), DotPlot(), DimPlot(), DoHeatmap() |
| Rename clusters | RenameIdents(obj, named_vector) |
| Module score | AddModuleScore(obj, features = list(genes), name = "score") |
| Cell cycle phase | CellCycleScoring(obj, s.features, g2m.features) |
| One panel per group | DimPlot(obj, split.by = "Phase") |
| Pseudobulk counts | AggregateExpression(obj, group.by = c("sample", "cell_type")) |
| Read a layer | LayerData(obj, layer = "data") |
| Values per cell | FetchData(obj, vars = c("ident", "LYZ")) |
| Split by sample | obj[["RNA"]] <- split(obj[["RNA"]], f = obj$sample) |
| Integrate | IntegrateLayers(obj, method = CCAIntegration) |
| Merge layers | obj[["RNA"]] <- JoinLayers(obj[["RNA"]]) |
| Merge objects | merge(obj_a, y = obj_b, add.cell.ids = c("a", "b")) |
| Save and read | saveRDS(obj, path) and readRDS(path) |
| Seurat 4 call | Seurat 5 call |
|---|---|
GetAssayData(obj, slot = "data") |
LayerData(obj, layer = "data") |
obj[["RNA"]]@counts |
obj[["RNA"]]$counts |
FindIntegrationAnchors() and IntegrateData() |
IntegrateLayers() |
UMAP_1 in FetchData() |
umap_1 |
FindMarkers() defaults min.pct = 0.1, logfc.threshold = 0.25 |
min.pct = 0.01, logfc.threshold = 0.1 |
Read the matrix
Section titled “Read the matrix”Read10X() reads a 10x directory with matrix.mtx, genes.tsv or features.tsv.gz, and
barcodes.tsv into a sparse genes by cells matrix.
The matrix is 3k PBMCs from a healthy donor, released by 10x Genomics with Cell Ranger 1.1.0 under CC BY 4.0. This lesson filters cells and genes, normalizes counts, and derives embeddings, markers, and figures from that matrix.
library(Seurat)library(dplyr)library(ggplot2)
dir.create("outputs", showWarnings = FALSE)set.seed(42)counts <- Read10X(data.dir = "/opt/data/pbmc3k")dim(counts)counts[c("CD3E", "MS4A1", "LYZ"), 1:3][1] 32738 27003 x 3 sparse Matrix of class "dgCMatrix" AAACATACAACCAC-1 AAACATTGAGCTAC-1 AAACATTGATCAGC-1CD3E 2 . 2MS4A1 . 6 .LYZ 1 3 2Create the object
Section titled “Create the object”min.cells drops genes seen in fewer than 3 cells, and min.features drops cells with
fewer than 200 genes. Of the 32,738 genes, 13,714 remain, and all 2,700 cells pass.
pbmc <- CreateSeuratObject(counts = counts, project = "pbmc3k", min.cells = 3, min.features = 200)pbmcAn object of class Seurat13714 features across 2700 samples within 1 assayActive assay: RNA (13714 features, 0 variable features) 1 layer present: countsQuality control
Section titled “Quality control”PercentageFeatureSet() adds the share of counts from mitochondrial genes to the
metadata. pbmc[[]] returns the metadata table.
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")head(pbmc[[]], 3) orig.ident nCount_RNA nFeature_RNA percent.mtAAACATACAACCAC-1 pbmc3k 2419 779 3.0177759AAACATTGAGCTAC-1 pbmc3k 4903 1352 3.7935958AAACATTGATCAGC-1 pbmc3k 3147 1129 0.8897363qc_features <- c("nFeature_RNA", "nCount_RNA", "percent.mt")qc_plot <- VlnPlot(pbmc, features = qc_features, ncol = 3, pt.size = 0.1)ggsave("outputs/seurat-qc-violin.png", qc_plot, width = 9, height = 4, dpi = 150, bg = "white")
subset() takes the cutoffs as an expression on the metadata columns. The upper
limit on genes removes likely doublets and the mitochondrial limit removes damaged
cells.
The Seurat 5.6.0 tutorial source contains the same QC thresholds and preprocessing sequence. Its source repository declares MIT and names the Seurat authors as copyright holders for 2021. The complete MIT notice accompanies this source comparison.
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & percent.mt < 5)ncol(pbmc)[1] 2638The filter keeps 2,638 of the 2,700 cells.
Normalize and select features
Section titled “Normalize and select features”NormalizeData() divides each cell by its total count, multiplies by 10,000 and takes
log1p. FindVariableFeatures() keeps the 2,000 genes with the highest standardized
variance.
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000, verbose = FALSE)pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000, verbose = FALSE)head(VariableFeatures(pbmc), 10) [1] "PPBP" "LYZ" "S100A9" "IGLL5" "GNLY" "FTL" "PF4" "FTH1" [9] "GNG11" "S100A8"top_variable <- head(VariableFeatures(pbmc), 10)var_plot <- LabelPoints(VariableFeaturePlot(pbmc), points = top_variable, repel = TRUE, xnudge = 0, ynudge = 0)ggsave("outputs/seurat-variable-features.png", var_plot, width = 7, height = 4.5, dpi = 150, bg = "white")
SCTransform() replaces these two steps and ScaleData() with one regularized negative
binomial model. It runs much faster with the glmGamPoi package, which this image does
not carry, so the page keeps the log normalization.
Scale and run PCA
Section titled “Scale and run PCA”ScaleData() centers and scales each gene. It scales the variable genes by default;
features = rownames(pbmc) scales every gene so that DoHeatmap() can draw any of them.
pbmc <- ScaleData(pbmc, features = rownames(pbmc), verbose = FALSE)pbmc <- RunPCA(pbmc, features = VariableFeatures(pbmc), verbose = FALSE)print(pbmc[["pca"]], dims = 1:2, nfeatures = 5)PC_ 1Positive: CST3, TYROBP, LST1, AIF1, FTLNegative: MALAT1, LTB, IL32, IL7R, CD2PC_ 2Positive: CD79A, MS4A1, TCL1A, HLA-DQA1, HLA-DQB1Negative: NKG7, PRF1, CST7, GZMB, GZMAPC 1 sets myeloid genes such as CST3, TYROBP and LST1 against T cell genes such as LTB,
IL7R and CD2. PC 2 sets the B cell genes CD79A and MS4A1 against the NK genes NKG7 and
PRF1. ElbowPlot() shows how much each PC adds.
elbow_plot <- ElbowPlot(pbmc, ndims = 30)ggsave("outputs/seurat-elbow.png", elbow_plot, width = 6, height = 4, dpi = 150, bg = "white")
The curve flattens after about PC 9, so the first 10 PCs carry the structure.
Cluster
Section titled “Cluster”FindNeighbors() builds a shared nearest neighbor graph on the first 10 PCs, and
FindClusters() runs Louvain on it. resolution sets how many clusters come out. Pass
random.seed so the partition repeats.
pbmc <- FindNeighbors(pbmc, dims = 1:10, verbose = FALSE)pbmc <- FindClusters(pbmc, resolution = 0.5, random.seed = 42, verbose = FALSE)table(Idents(pbmc)) 0 1 2 3 4 5 6 7 8705 481 472 344 274 162 155 32 13Resolution 0.5 gives nine clusters, from 705 cells in cluster 0 to 13 in cluster 8.
RunUMAP() embeds the same 10 PCs in two dimensions for plotting. seed.use fixes the
layout.
pbmc <- RunUMAP(pbmc, dims = 1:10, seed.use = 42, verbose = FALSE)umap_plot <- DimPlot(pbmc, reduction = "umap", label = TRUE) + NoLegend()ggsave("outputs/seurat-umap-clusters.png", umap_plot, width = 6, height = 5, dpi = 150, bg = "white")
Find markers
Section titled “Find markers”FindAllMarkers() tests each cluster against all other cells with a Wilcoxon test.
Seurat 5 lowered the defaults to min.pct = 0.01 and logfc.threshold = 0.1, from 0.1
and 0.25 in Seurat 4. The call below passes 0.25 for both to keep the list short.
markers <- FindAllMarkers(pbmc, only.pos = TRUE, min.pct = 0.25, logfc.threshold = 0.25, verbose = FALSE)markers |> group_by(cluster) |> slice_max(avg_log2FC, n = 2, with_ties = FALSE) |> select(cluster, gene, avg_log2FC, pct.1, pct.2)# A tibble: 18 × 5# Groups: cluster [9] cluster gene avg_log2FC pct.1 pct.2 <fct> <chr> <dbl> <dbl> <dbl> 1 0 CCR7 2.39 0.44 0.108 2 0 LEF1 2.09 0.333 0.104 3 1 FOLR3 7.28 0.299 0.004 4 1 S100A12 6.74 0.277 0.006 5 2 AQP3 2.12 0.426 0.111 6 2 CD40LG 1.90 0.267 0.069 7 3 LINC00926 7.38 0.564 0.009 8 3 VPREB3 7.14 0.488 0.007 9 4 GZMK 4.25 0.588 0.05810 4 GZMH 3.77 0.442 0.0611 5 CKB 5.88 0.37 0.00512 5 CDKN1C 5.43 0.506 0.0113 6 AKR1C3 6.22 0.471 0.01314 6 SH2D1B 6.07 0.29 0.00715 7 SERPINF1 8.03 0.5 0.00216 7 FCER1A 7.63 0.812 0.01117 8 LY6G6F 14.4 0.615 018 8 RP11-879F14.2 13.9 0.385 0The largest fold changes often belong to genes that only part of the cluster expresses.
FOLR3 tops cluster 1 at a log2 fold change of 7.28 and is detected in 29.9 percent of
its cells, so read pct.1 next to avg_log2FC. Without the presto package, which this
image does not carry, Seurat falls back to a slower Wilcoxon implementation and says so
once in a message.
Plot genes
Section titled “Plot genes”FeaturePlot() colors the UMAP by the expression of each gene.
feature_plot <- FeaturePlot(pbmc, features = c("CD3E", "MS4A1", "CD14", "NKG7"), ncol = 2)ggsave("outputs/seurat-feature-plot.png", feature_plot, width = 8, height = 7, dpi = 150, bg = "white")
DotPlot() shows a panel of known markers for every cluster at once. Dot size is the
percent of cells that express the gene, and color is the scaled mean expression.
marker_genes <- c("IL7R", "CCR7", "S100A4", "CD8A", "MS4A1", "CD14", "LYZ", "FCGR3A", "MS4A7", "GNLY", "NKG7", "FCER1A", "CST3", "PPBP")dot_plot <- DotPlot(pbmc, features = marker_genes) + RotatedAxis()ggsave("outputs/seurat-dot-plot.png", dot_plot, width = 9, height = 4.5, dpi = 150, bg = "white")
Name the clusters
Section titled “Name the clusters”The dot plot gives one cell type per cluster. RenameIdents() takes a named vector from
the old identity to the new one.
cell_types <- c( "0" = "Naive CD4 T", "1" = "CD14+ Mono", "2" = "Memory CD4 T", "3" = "B", "4" = "CD8 T", "5" = "FCGR3A+ Mono", "6" = "NK", "7" = "DC", "8" = "Platelet")pbmc <- RenameIdents(pbmc, cell_types)pbmc$cell_type <- Idents(pbmc)table(Idents(pbmc)) Naive CD4 T CD14+ Mono Memory CD4 T B CD8 T FCGR3A+ Mono 705 481 472 344 274 162 NK DC Platelet 155 32 13named_plot <- DimPlot(pbmc, reduction = "umap", label = TRUE, repel = TRUE) + NoLegend()ggsave("outputs/seurat-umap-named.png", named_plot, width = 6, height = 5, dpi = 150, bg = "white")
Compare two cell types
Section titled “Compare two cell types”FindMarkers() tests one group of cells against another. The identities can now be the
cell type names.
mono_markers <- FindMarkers(pbmc, ident.1 = "FCGR3A+ Mono", ident.2 = "CD14+ Mono", verbose = FALSE)head(mono_markers, 5) p_val avg_log2FC pct.1 pct.2 p_val_adjFCGR3A 8.281327e-102 5.022529 0.975 0.131 1.135701e-97LYZ 8.058992e-75 -2.653109 0.988 1.000 1.105210e-70RHOC 3.304501e-68 3.322105 0.864 0.162 4.531792e-64S100A8 8.561964e-65 -4.014311 0.500 0.975 1.174188e-60S100A9 1.506661e-64 -3.393369 0.870 0.996 2.066235e-60A positive avg_log2FC means higher in ident.1. FCGR3A is up 5.02 log2 units in the
FCGR3A+ monocytes, while S100A8, S100A9 and LYZ are higher in the CD14+ monocytes.
Module scores
Section titled “Module scores”AddModuleScore() scores each cell on a gene set as the mean expression of the set minus
that of random control genes with similar expression. seed fixes the control genes, and
the score lands in a metadata column named name plus 1.
cytotoxic_genes <- c("GZMA", "GZMB", "GZMH", "PRF1", "NKG7", "GNLY", "CST7")pbmc <- AddModuleScore(pbmc, features = list(cytotoxic_genes), name = "cytotoxic", seed = 42)pbmc[[]] |> group_by(cell_type) |> summarise(cytotoxic = round(mean(cytotoxic1), 2)) |> arrange(desc(cytotoxic))# A tibble: 9 × 2 cell_type cytotoxic <fct> <dbl>1 NK 2.632 CD8 T 1.133 Platelet -0.244 Naive CD4 T -0.375 Memory CD4 T -0.46 B -0.417 CD14+ Mono -0.468 DC -0.519 FCGR3A+ Mono -0.53NK cells score 2.63 and CD8 T cells 1.13, while every other cell type scores below zero.
Cell cycle phase
Section titled “Cell cycle phase”CellCycleScoring() scores S and G2M genes and assigns a phase per cell.
cc.genes.updated.2019 ships with Seurat and holds the current gene symbols.
set.ident = FALSE keeps the cell type identities.
The cell cycle lists come from Seurat’s cc.genes.updated.2019 object, whose data reference credits Tirosh and colleagues, 2016. The object retains 43 S-phase and 54 G2M genes and changes six symbols from cc.genes. The Seurat 5.6.0 source distribution includes both objects under MIT; the complete notice credits the Seurat authors. This lesson uses the updated lists to derive scores and phase labels.
pbmc <- CellCycleScoring(pbmc, s.features = cc.genes.updated.2019$s.genes, g2m.features = cc.genes.updated.2019$g2m.genes, set.ident = FALSE, seed = 42)summary(pbmc[[c("S.Score", "G2M.Score")]])table(pbmc$cell_type, pbmc$Phase) S.Score G2M.Score Min. :-0.0715677 Min. :-0.105599 1st Qu.:-0.0326925 1st Qu.:-0.053726 Median :-0.0114577 Median :-0.024818 Mean :-0.0002526 Mean :-0.019160 3rd Qu.: 0.0199989 3rd Qu.: 0.006631 Max. : 0.5967665 Max. : 0.805348
G1 G2M S Naive CD4 T 260 162 283 CD14+ Mono 256 102 123 Memory CD4 T 143 119 210 B 135 67 142 CD8 T 101 66 107 FCGR3A+ Mono 86 32 44 NK 49 38 68 DC 15 6 11 Platelet 5 7 1Read the scores before the phases. A cell is called G1 only when both scores fall below
zero, and otherwise takes the phase with the higher score. Most PBMCs do not divide.
The median S score is -0.011 and three quarters of the cells score below 0.02, so many S
and G2M calls rest on scores just above zero. Seurat
also warns that 16 of the genes are missing. Twelve were dropped by min.cells = 3, and
four are absent from the gene annotation of PBMC 3k, which lists PIMREG and JPT1 under
their older symbols FAM64A and HN1.
Split a plot
Section titled “Split a plot”split.by draws one panel per value of a metadata column.
phase_plot <- DimPlot(pbmc, reduction = "umap", group.by = "cell_type", split.by = "Phase", ncol = 3)ggsave("outputs/seurat-umap-phase.png", phase_plot, width = 13, height = 4.5, dpi = 150, bg = "white")
Pseudobulk
Section titled “Pseudobulk”AggregateExpression() sums the counts of every cell in a group into one column. With
several samples, group.by = c("sample", "cell_type") gives the sample by cell type
matrix that DESeq2 or limma tests.
pseudobulk <- AggregateExpression(pbmc, group.by = "cell_type", assays = "RNA")$RNAdim(pseudobulk)pseudobulk[c("CD3E", "MS4A1", "LYZ"), 1:4][1] 13714 93 x 4 sparse Matrix of class "dgCMatrix" Naive CD4 T CD14+ Mono Memory CD4 T BCD3E 1125 53 990 43MS4A1 30 28 31 756LYZ 458 22215 387 215The result is a sparse genes by groups matrix of summed raw counts, 13,714 genes by 9 cell types here. LYZ sums to 22,215 counts in the CD14+ monocytes.
Layers and data access
Section titled “Layers and data access”Seurat 5 stores each matrix of an assay as a layer, named counts, data for the
normalized values, and scale.data. LayerData() reads one. Seurat 4 code reads the same matrix
with GetAssayData(pbmc, slot = "data") or pbmc[["RNA"]]@data. SeuratObject 5
deprecates slot in favor of layer.
Layers(pbmc)LayerData(pbmc, layer = "data")[c("CD3E", "LYZ"), 1:3][1] "counts" "data" "scale.data"2 x 3 sparse Matrix of class "dgCMatrix" AAACATACAACCAC-1 AAACATTGAGCTAC-1 AAACATTGATCAGC-1CD3E 2.226555 . 1.995416LYZ 1.635873 1.962726 1.995416FetchData() pulls metadata, embeddings and genes into one data frame per cell. The
UMAP columns are umap_1 and umap_2 in Seurat 5, where Seurat 4 named them UMAP_1
and UMAP_2.
FetchData(pbmc, vars = c("ident", "nCount_RNA", "umap_1", "LYZ")) |> head(3) ident nCount_RNA umap_1 LYZAAACATACAACCAC-1 Memory CD4 T 2419 2.864640 1.635873AAACATTGAGCTAC-1 B 4903 5.019568 1.962726AAACATTGATCAGC-1 Memory CD4 T 3147 4.590423 1.995416Split layers and integrate
Section titled “Split layers and integrate”Seurat 5 integrates samples that live in one object, with one layer per sample.
split() makes those layers. PBMC 3k is a single sample, so the split below cuts it
into two halves by alternate cells. It shows the calls and the layer names; it corrects
no real batch.
pbmc_lanes <- CreateSeuratObject(counts = LayerData(pbmc, layer = "counts"))pbmc_lanes$lane <- rep(c("lane_a", "lane_b"), length.out = ncol(pbmc_lanes))pbmc_lanes[["RNA"]] <- split(pbmc_lanes[["RNA"]], f = pbmc_lanes$lane)Layers(pbmc_lanes)[1] "counts.lane_a" "counts.lane_b"The usual steps run on every layer, and IntegrateLayers() adds a corrected
reduction. CCAIntegration ships with Seurat; HarmonyIntegration needs the harmony
package, which this image does not carry.
pbmc_lanes <- pbmc_lanes |> NormalizeData(verbose = FALSE) |> FindVariableFeatures(verbose = FALSE) |> ScaleData(verbose = FALSE) |> RunPCA(verbose = FALSE) |> IntegrateLayers(method = CCAIntegration, orig.reduction = "pca", new.reduction = "integrated.cca", verbose = FALSE)Reductions(pbmc_lanes)[1] "pca" "integrated.cca"Run FindNeighbors(reduction = "integrated.cca") and RunUMAP() on the new reduction
to cluster the integrated cells. JoinLayers() then merges the layers of the samples
back into one, which FindMarkers() needs.
pbmc_lanes[["RNA"]] <- JoinLayers(pbmc_lanes[["RNA"]])Layers(pbmc_lanes)[1] "data" "counts" "scale.data"Seurat 4 tutorials integrate a list of objects with FindIntegrationAnchors() and
IntegrateData(). Both still exist in Seurat 5, but IntegrateLayers() is the
Seurat 5 route.
Merge objects and save
Section titled “Merge objects and save”merge() joins two objects and keeps one counts layer per object, ready for
IntegrateLayers() or JoinLayers(). add.cell.ids prefixes the barcodes so that they
stay unique.
counts_filtered <- LayerData(pbmc, layer = "counts")pbmc_a <- CreateSeuratObject(counts_filtered[, 1:1319], project = "half_a")pbmc_b <- CreateSeuratObject(counts_filtered[, 1320:2638], project = "half_b")pbmc_merged <- merge(pbmc_a, y = pbmc_b, add.cell.ids = c("a", "b"))Layers(pbmc_merged)head(Cells(pbmc_merged), 2)[1] "counts.half_a" "counts.half_b"[1] "a_AAACATACAACCAC-1" "a_AAACATTGAGCTAC-1"saveRDS() writes the whole object to one file, and readRDS() reads it back.
rds_path <- tempfile(fileext = ".rds")saveRDS(pbmc_merged, rds_path)pbmc_read <- readRDS(rds_path)identical(Cells(pbmc_read), Cells(pbmc_merged))table(pbmc_read$orig.ident)[1] TRUE
half_a half_b 1319 1319The object reads back with the same 2,638 cells and keeps its two layers. In a project, write the file next to the analysis outputs rather than to a temporary path.
See also
Section titled “See also”- Quality Control computes the same metrics on PBMC 3k in Scanpy and filters on MADs instead of fixed cutoffs.
- Clustering sweeps the resolution and compares the partitions.
- Annotation ranks cluster markers with the Wilcoxon test and names the clusters.
- Integration corrects a real batch between two 10x chemistries.
- Single-Cell Formats covers the 10x matrix directory, H5AD and Seurat RDS files.
Scientific references
Section titled “Scientific references”Hao and colleagues, 2023 describe the Seurat methods for integrative, multimodal, and scalable single-cell analysis.
Further reading
Section titled “Further reading”The PBMC3k tutorial explains the QC thresholds, variable genes, neighborhood graph, and marker comparisons used in the corresponding workflow. Its parameter choices fit this dataset, and another experiment needs its own thresholds.
The Seurat 5.6.0 source references include LayerData dependencies, IntegrateLayers.Rd, AggregateExpression.Rd, and cc.genes.updated.2019.Rd. The integration and aggregation references distinguish an artificial lane demonstration from biological replication. The cell-cycle data reference records the Tirosh source and the six updated gene symbols.