Which cells belong together? This lesson reduces 2,000 genes to 10 principal components, groups the cells on a neighbour graph, draws them with UMAP, and shows what that map does not tell you.
PCA on the variable genes
Single-cell QC and normalisation left you with 2,635 clean cells, log-normalised, with 2,000 variable genes scaled and saved in pbmc_qc.rds. This lesson finds the groups of similar cells inside them.
The first step is the PCA of Clustering, PCA and heatmaps, now with cells in place of tumours. Two thousand genes are too many dimensions to compare cells in directly: most of the differences between any two cells are counting noise. PCA concentrates the shared, structured variation into a few components, and the later steps work on those.
library(Seurat)
library(ggplot2)
pbmc <- readRDS("pbmc_qc.rds")
pbmc <- RunPCA(pbmc, features = VariableFeatures(pbmc), npcs = 50, verbose = FALSE)
print(pbmc[["pca"]], dims = 1:2, nfeatures = 6)
sdev <- pbmc[["pca"]]@stdev
round(100 * sdev^2 / sum(sdev^2), 1)[1:15]
ElbowPlot(pbmc, ndims = 30) + theme_classic()What this does
RunPCA()runs PCA on the scaled values of the variable genes and stores 50 components inpbmc[["pca"]]. Each cell gets a score on each component, as each tumour did withprcomp().print(..., nfeatures = 6)lists the genes with the largest positive and negative loadings, the weights that say how much each gene contributes to a component.- The next line is the percentage-of-variance formula from Clustering, PCA and heatmaps. Seurat computes only the first 50 components, so these are shares of the variance those 50 capture, not of all the variation in the data.
ElbowPlot()draws each component's standard deviation against its number.
The loadings already read as biology. PC1 sets myeloid genes such as CST3, TYROBP, LST1 and AIF1, typical of monocytes, against lymphocyte genes such as LTB, IL7R and CD2. PC2 separates cytotoxic genes (NKG7, PRF1, GZMB), found in NK cells and some T cells, from B-cell genes (CD79A, MS4A1). Nobody told PCA which cells are which; the strongest patterns in the data happen to be the differences between cell types.
Choosing how many components
The elbow plot falls steeply over the first six or seven components, then flattens from about the ninth: the later components each add a little and look alike, the pattern expected when they mostly hold noise. This lesson keeps the first 10. The choice is a judgement, made by looking, like the QC thresholds. Too few components can merge cell types that differ only in later ones; too many add noise, though Seurat's later steps are fairly tolerant of that. When in doubt, repeat the clustering with, say, 15 components and check whether the groups you care about stay the same.
From neighbours to clusters
In Clustering, PCA and heatmaps you grouped 150 tumours with hierarchical clustering and k-means. With thousands of cells and groups of very different sizes, single-cell analysis usually turns the data into a graph instead: a network in which each cell is a point and lines join cells that are similar. Groups are then found as parts of the network that are densely joined inside and loosely joined to the rest.
pbmc <- FindNeighbors(pbmc, dims = 1:10, k.param = 20) pbmc <- FindClusters(pbmc, resolution = 0.5, random.seed = 1) table(Idents(pbmc))
What this does
FindNeighbors()finds, for every cell, its 20 nearest cells in the space of the first 10 principal components: the k-nearest-neighbour (kNN) graph, with k = 20. It then builds a shared-nearest-neighbour (SNN) graph, in which two cells are joined more strongly the more neighbours they have in common. Sharing neighbours is a sturdier sign of belonging together than being close once, because one noisy distance cannot create it.FindClusters()runs the Louvain algorithm on the SNN graph. It moves cells between groups to raise the modularity, a score of how much more densely the groups are joined inside than a random network would be. A value of 0.87 indicates strong group structure. The search starts from random positions, sorandom.seedmakes the result reproducible.- The result is nine clusters, numbered from the largest, 720 cells, to the smallest, 12. Seurat sets them as the cells' identities, which
Idents()returns and later functions use by default.
Worked example · how strongly are two cells joined?
Seurat weights each pair of cells by the Jaccard index of their neighbour lists: the neighbours they share, divided by all the distinct neighbours either has. Take k = 20:
distinct neighbours in total = 20 + 20 − 15 = 25
Jaccard = 15 ÷ 25 = 0.60
cells A and C share 2: 2 ÷ (20 + 20 − 2) = 2 ÷ 38 = 0.05
What the answer means. A and B sit in the same crowd, so the link between them is strong. A and C may be close in distance, but they move in different crowds. By default Seurat removes links weaker than 1/15, about 0.067, so the A–C link is dropped and only A–B remains.
The graph had 95,890 links among 2,635 cells after this pruning: on average each cell keeps links to a few dozen others.
Resolution: how finely to split
The resolution argument sets how small the groups are allowed to be. Higher values give more, smaller clusters. No value is correct in general; it depends on the question. Running several values and cross-tabulating them, as you cross-tabulated clusters with subtypes in Module 5, shows how groups split.
for (r in c(0.1, 0.3, 0.5, 0.8, 1.2)) {
pbmc <- FindClusters(pbmc, resolution = r, random.seed = 1, verbose = FALSE)
}
sapply(c("RNA_snn_res.0.1", "RNA_snn_res.0.3", "RNA_snn_res.0.5",
"RNA_snn_res.0.8", "RNA_snn_res.1.2"),
function(col) length(unique(pbmc[[col, drop = TRUE]])))
table(res0.1 = pbmc$RNA_snn_res.0.1, res0.5 = pbmc$RNA_snn_res.0.5)
Idents(pbmc) <- "RNA_snn_res.0.5"Reading the output
Each run adds a column named after its resolution to the cell data, so nothing is overwritten. Four clusters at 0.1 become nine at 0.5 and eleven at 0.8 and 1.2. The cross-table shows that the splits are clean: almost every cluster at 0.5 lies inside one cluster at 0.1. Coarse cluster 1 divides into clusters 1, 5, 7 and 8; coarse cluster 0 into 0 and 2. That nesting is reassuring: the fine clusters are subdivisions of the coarse ones, not a different cut of the data.
Whether a fine split is biology or noise is not something the clustering can tell you. Clusters 0 and 2 might be two kinds of T cell or one kind cut in half. Markers and cell types answers that by asking which genes each cluster expresses. The last line sets the 0.5 clustering as the identities for the rest of the module.
Go deeper: Louvain, Leiden and k-means
Louvain can occasionally produce a cluster whose cells are poorly connected to each other. The Leiden algorithm (Traag, Waltman & van Eck 2019) fixes this and is often preferred; in Seurat it is FindClusters(pbmc, algorithm = 4), which needs an extra package.
k-means from Module 5 can be run on the same 10 PC scores: kmeans(Embeddings(pbmc, "pca")[, 1:10], centers = 9, nstart = 25). In this dataset it agreed with Louvain on the clearly separated groups but drew a different line through the two large clusters 0 and 2, putting 578 of cluster 0's cells in one k-means group and most of cluster 2's 468 with 129 cells of cluster 0 in another. k-means looks for round groups of similar size; the graph method allows groups of any shape and size, which suits cell types better.
UMAP: a map, not a measurement
Ten components are still too many to look at. UMAP (uniform manifold approximation and projection) draws the cells in two dimensions, trying to keep each cell next to the cells that were its neighbours in the 10-dimensional PCA space. It is the picture almost every single-cell paper shows.
pbmc <- RunUMAP(pbmc, dims = 1:10, seed.use = 42, verbose = FALSE)
DimPlot(pbmc, reduction = "umap", label = TRUE) + theme_classic() + NoLegend()
pbmc_b <- RunUMAP(pbmc, dims = 1:10, seed.use = 42, verbose = FALSE)
identical(Embeddings(pbmc, "umap"), Embeddings(pbmc_b, "umap"))
u7 <- RunUMAP(pbmc, dims = 1:10, seed.use = 7, verbose = FALSE,
reduction.name = "umap7")
head(Embeddings(pbmc, "umap"), 2)
head(Embeddings(u7, "umap7"), 2)
saveRDS(pbmc, "pbmc_clustered.rds")What this does
RunUMAP()uses the same 10 components as the clustering and stores two coordinates per cell.DimPlot()draws them, coloured by the current identities.- UMAP starts from a random layout. With the same
seed.use, the second run gives identical coordinates; with a different seed, every coordinate moves. Set the seed, as you usedset.seed()before k-means and random forests in Module 5, and report it. saveRDS()keeps the clustered object for Markers and cell types.
On the plot the nine clusters fall into three well-separated islands: one holding clusters 0, 2, 4 and 6, one holding 1, 5 and 7, and cluster 3 on its own, with the 12 cells of cluster 8 as a dot between them. The clusters were found in the PCA space; UMAP only draws them. A cluster that looks split on the map is still one cluster, and two clusters that touch on the map were still kept apart by the graph.
What the map does not show
UMAP keeps local neighbourhoods well but bends everything else. Three checks on this map, comparing it with the 10-dimensional PCA space it was drawn from, show how much.
emb_pca <- Embeddings(pbmc, "pca")[, 1:10]
emb_umap <- Embeddings(pbmc, "umap")
cl <- Idents(pbmc)
set.seed(1)
idx <- sample(ncol(pbmc), 500)
round(cor(as.vector(dist(emb_pca[idx, ])), as.vector(dist(emb_umap[idx, ])),
method = "spearman"), 2)
cent_pca <- apply(emb_pca, 2, function(v) tapply(v, cl, mean))
cent_umap <- apply(emb_umap, 2, function(v) tapply(v, cl, mean))
round(cor(as.vector(dist(cent_pca)), as.vector(dist(cent_umap)),
method = "spearman"), 2)
spread <- function(emb) tapply(seq_len(nrow(emb)), cl,
function(i) mean(dist(emb[i, , drop = FALSE])))
round(cbind(n = as.vector(table(cl)), pca = spread(emb_pca), umap = spread(emb_umap)), 2)Reading the output
- For 500 random cells, the rank correlation between their distances in PCA space and on the map is 0.66: related, but far from faithful.
- For the distances between the nine cluster centres it falls to 0.23. Which islands sit near each other, and how far apart, says little about how different the cell types are.
- The spread of a cluster, the average distance between its cells, is not kept either. Cluster 8 is the most spread-out group in PCA space, 19.93, yet on the map it is a dot, 0.06. UMAP tends to draw small groups tight and large groups wide, whatever their real variability.
So read a UMAP for its neighbourhoods: which cells sit with which, and whether a cluster forms one group. Do not read sizes, densities or the gaps between islands as measurements, and never test anything on UMAP coordinates. t-SNE, an older method you may meet in papers, has the same limits.
Common mistakes
- Clustering on the UMAP. Cluster on the PCA-based graph. The map is for looking.
- Reading distances on the map. Islands far apart are not necessarily very different, and a large blob is not necessarily a variable cell type.
- Treating the resolution as a discovery. More clusters at a higher resolution is a setting, not a finding. Decide whether each split is real from its marker genes.
- Forgetting the seeds. Without
random.seedandseed.use, the cluster numbers and the map can change between runs.
The Louvain method is from Blondel et al. 2008 (Journal of Statistical Mechanics), and Leiden from Traag, Waltman & van Eck 2019 (Scientific Reports). UMAP was introduced by McInnes, Healy & Melville in 2018 (arXiv), and Becht et al. 2019 (Nature Biotechnology) compared it with t-SNE for single-cell data. Chari & Pachter 2023, "The specious art of single-cell genomics" (PLoS Computational Biology), shows in detail how two-dimensional maps distort distances between cells and clusters. In methods, report the number of PCs, k, the resolution, the clustering algorithm and the seeds.
Key point
Clusters come from a graph built on principal components; UMAP only draws them. Choose the number of PCs and the resolution by looking, set the seeds, and read the map for neighbourhoods, not for distances or sizes.
Further reading · Module 6Chari & Pachter 2023: what two-dimensional embeddings of cells can and cannot show. · All reading for this course
Check your understanding
1. You raise the clustering resolution from 0.5 to 0.8 and get 11 clusters instead of 9. What have you learned?
2. Two clusters sit far apart on a UMAP plot. What can you conclude?
3. Why does Seurat join cells by shared nearest neighbours rather than by distance alone?