Annotation
Clustering gives each cell a number. Annotation turns each number into a cell type, and it is the most subjective step of the workflow. This page ranks the genes that set each Leiden cluster apart, checks them against known PBMC markers, and names the five clusters.
Load, filter, embed, cluster
Section titled “Load, filter, embed, cluster”The setup repeats the steps of the earlier pages, from Quality Control to Clustering, and ends with the five Leiden clusters at resolution 0.5.
Setup code and its output
The MAD helper below adapts cells 18, 20 and 22 of the archived quality-control notebook. This version computes MAD with pandas and changes the filter combination. The source is copyright 2021 Theislab under Apache 2.0.
The source matrix is 10x Genomics’ PBMC 3k dataset, processed with Cell Ranger 1.1.0 and published in 2016. The provider licenses it under CC BY 4.0. This lesson converts the matrix to AnnData and derives the displayed summaries and analysis results.
import numpy as npimport scanpy as scimport matplotlib.pyplot as plt
sc.settings.verbosity = 3np.random.seed(42)
adata = sc.read_10x_mtx("/opt/data/pbmc3k", var_names="gene_symbols", make_unique=True)adata.layers["counts"] = adata.X.copy()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)
def is_outlier(adata, metric, nmads): """Flag cells whose metric sits more than nmads MADs from the median.
Args: adata: AnnData object holding the metric in .obs. metric: Column of adata.obs to test. nmads: Number of median absolute deviations for the cutoff.
Returns: Boolean Series, True where the cell is an outlier. """ values = adata.obs[metric] median = values.median() mad = (values - median).abs().median() return (values < median - nmads * mad) | (values > median + nmads * mad)
adata.obs["log1p_total_counts"] = np.log1p(adata.obs["total_counts"])adata.obs["log1p_n_genes_by_counts"] = np.log1p( adata.obs["n_genes_by_counts"])adata.obs["outlier"] = ( is_outlier(adata, "log1p_total_counts", 5) | is_outlier(adata, "log1p_n_genes_by_counts", 5) | is_outlier(adata, "pct_counts_mt", 3))adata = adata[~adata.obs["outlier"]].copy()sc.pp.filter_genes(adata, min_cells=3)
sc.pp.normalize_total(adata, target_sum=1e4)sc.pp.log1p(adata)sc.pp.highly_variable_genes(adata, layer="counts", n_top_genes=2000, flavor="seurat_v3")adata.raw = adataadata = adata[:, adata.var["highly_variable"]]sc.pp.scale(adata, max_value=10)sc.tl.pca(adata, n_comps=50, random_state=42)sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30, random_state=42)sc.tl.umap(adata, random_state=42)sc.tl.leiden(adata, resolution=0.5, key_added="leiden", random_state=42, flavor="igraph", n_iterations=2, directed=False)print(adata.obs["leiden"].value_counts().sort_index())leiden0 10991 4562 4123 3154 146Name: count, dtype: int64Markers from the data
Section titled “Markers from the data”The first pass asks the data which genes set each cluster apart. rank_genes_groups tests every gene in one cluster against all other cells with the Wilcoxon rank-sum test. A cell-level test is the right tool here, because the question is how groups of cells in one dataset differ. Between conditions it is the wrong tool, for the reasons on the Differential Expression page.
sc.tl.rank_genes_groups(adata, groupby="leiden", method="wilcoxon")
result_df = sc.get.rank_genes_groups_df(adata, group="0")print(result_df.head(8).to_string(index=False))names scores logfoldchanges pvals pvals_adj LDHB 31.944715 2.778137 6.397028e-224 8.619356e-220RPS12 30.740160 0.983159 1.655289e-207 7.434454e-204RPS25 29.029331 1.140002 2.806448e-185 7.562817e-182RPS27 28.159712 0.985933 1.822450e-174 3.069462e-171 RPS6 27.788717 0.823007 5.937959e-170 8.889784e-167 RPS3 27.520372 0.834473 1.001657e-166 1.349632e-163 TPT1 27.140507 0.925139 3.277350e-162 3.396847e-159 CD3D 26.998106 3.200113 1.555552e-160 1.497108e-157The top genes of cluster 0 are LDHB, five ribosomal protein genes and TPT1, and CD3D, the T cell marker, comes eighth. The ribosomal genes have a log2 fold change near 1, against 3.20 for CD3D, and they still rank higher, because the Wilcoxon score measures how consistently the ranks shift, not how far. Ribosomal protein genes are detected in nearly every cell, so a modest rise lifts the whole of cluster 0 above the other cells. CD3D is zero in some cluster 0 cells and is also expressed by the T cells of cluster 2, so its values overlap more between the two groups, and the tied zeros lower its score further. Resting T cells also carry more ribosomal transcripts than monocytes, so part of the shift is biology, but a ribosomal gene alone does not name a cell type.
result = adata.uns["rank_genes_groups"]groups = result["names"].dtype.names
for group in groups: top = result["names"][group][:3] print(f"{group}: {', '.join(top)}")0: LDHB, RPS12, RPS251: LYZ, S100A9, CST32: NKG7, CST7, CCL53: CD74, CD79A, HLA-DRA4: LST1, FCER1G, FCGR3AClusters 1 to 4 show clear identities in their top three genes. LYZ, S100A9 and CST3 point to classical monocytes, NKG7, CST7 and CCL5 to cytotoxic cells, CD74, CD79A and HLA-DRA to B cells, and LST1, FCER1G and FCGR3A to FCGR3A+ monocytes.
sc.pl.rank_genes_groups_dotplot(adata, n_genes=4, groupby="leiden", show=False)plt.savefig("outputs/annotation_rank-dotplot.png", dpi=150, bbox_inches="tight")plt.close()
sc.pl.rank_genes_groups_heatmap(adata, n_genes=5, show_gene_labels=False, show=False)plt.savefig("outputs/annotation_rank-heatmap.png", dpi=150, bbox_inches="tight")plt.close()
The dot plot and the heatmap show how specific each marker is. CD79A and CD79B are dark in the cluster 3 row only, and the cytotoxic genes of cluster 2 in its row only. HLA-DRA, an MHC class II gene, and CD74, the invariant chain that guides class II molecules through the cell, are dark in clusters 1, 3 and 4, because B cells and monocytes both present antigen on MHC class II.
Known markers
Section titled “Known markers”The second pass starts from biology. Manual annotation checks the marker genes that the literature ties to each cell type, cluster by cluster. It needs knowledge of the tissue, because the same cell type can express different markers in different tissues.
markers = { "T cells": ["CD3D", "CD3E"], "B cells": ["MS4A1", "CD79A"], "Monocytes": ["CD14", "LYZ"], "NK cells": ["GNLY", "NKG7"], "DC": ["FCER1A", "CST3"],}
sc.pl.umap(adata, color=["CD3D", "MS4A1", "CD14", "GNLY"], use_raw=True, show=False)plt.savefig("outputs/annotation_marker-umap.png", dpi=150, bbox_inches="tight")plt.close()
sc.pl.dotplot(adata, markers, groupby="leiden", use_raw=True, show=False)plt.savefig("outputs/annotation_dotplot.png", dpi=150, bbox_inches="tight")plt.close()
The known markers agree with the ranking. CD3D covers the left group, MS4A1 the bottom group, CD14 the right group and GNLY the top of the left group. The DC markers do not pick out a cluster. FCER1A is weak everywhere and CST3 follows the monocytes, so at this resolution PBMC 3k has no separate dendritic cell cluster.
Marker scores
Section titled “Marker scores”# score_genes averages a marker set and subtracts a matched control# set, so each cluster gets one number per candidate identity.marker_sets = { "T cells": ["CD3D", "CD3E", "IL7R"], "B cells": ["MS4A1", "CD79A", "CD79B"], "Monocytes": ["CD14", "LYZ", "S100A9"], "NK cells": ["GNLY", "NKG7", "KLRD1"], "DC": ["FCER1A", "CST3", "CLEC10A"],}
for name, genes in marker_sets.items(): sc.tl.score_genes(adata, gene_list=genes, score_name=f"score_{name}", use_raw=True) scores = adata.obs.groupby("leiden", observed=True)[ f"score_{name}" ].mean() print(f"{name:10s} top cluster {scores.idxmax()} ({scores.max():.3f})")T cells top cluster 0 (0.555)B cells top cluster 3 (1.891)Monocytes top cluster 1 (2.770)NK cells top cluster 2 (1.572)DC top cluster 1 (0.808)Each marker set scores highest in the cluster that the ranking pointed to. The monocyte set gives the strongest top score, 2.770 in cluster 1, and the T cell set the weakest, 0.555 in cluster 0. The DC set also peaks in cluster 1, at 0.808, because CST3 belongs to both the DC and the monocyte profile.
From clusters to cell types
Section titled “From clusters to cell types”Cluster 2 needs one more check before it gets a name. Its top genes, NKG7, CST7 and CCL5, are cytotoxic genes that NK cells and CD8 T cells share, and none of the plots above shows CD8A. The next block prints, for each cluster, the fraction of cells that detect CD8A, the T cell marker CD3D, the NK gene GNLY and the shared cytotoxic gene NKG7. It then splits cluster 2 by CD3D and GNLY and gives the number of cells and the CD8A fraction of each part.
# A cell detects a gene when the gene's count is above zero. obs_df# reads adata.raw, which holds every gene that passed the gene filter# as log1p of the normalized count, and that value is above zero only# when the count is.check_genes = ["CD8A", "CD3D", "GNLY", "NKG7"]detected = sc.get.obs_df(adata, keys=check_genes, use_raw=True) > 0detected["leiden"] = adata.obs["leiden"]print(detected.groupby("leiden", observed=True).mean().round(3))
cluster_2 = detected[detected["leiden"] == "2"]split = cluster_2.groupby(["CD3D", "GNLY"])["CD8A"].agg( cells="size", CD8A="mean")print(split.round(3)) CD8A CD3D GNLY NKG7leiden0 0.104 0.876 0.104 0.1451 0.020 0.099 0.138 0.2082 0.364 0.612 0.541 0.9643 0.022 0.060 0.086 0.0834 0.041 0.075 0.158 0.322 cells CD8ACD3D GNLYFalse False 18 0.556 True 142 0.085True False 171 0.538 True 81 0.444CD8A is detected in 0.364 of the cluster 2 cells, against 0.104 in cluster 0 and 0.041 or less in the other three clusters, while NKG7 reaches 0.964 in cluster 2. CD8A is more frequent in cluster 2, but it does not separate the two clusters, because most cells in both show no CD8A count. The split shows two main groups inside cluster 2. The 142 cells with GNLY and no CD3D detect CD8A at 0.085, which fits NK cells. The 171 cells with CD3D and no GNLY detect CD8A at 0.538, and the 81 cells with both genes at 0.444, which fits CD8 T cells, since effector CD8 T cells also make GNLY. The other 18 cells detect neither CD3D nor GNLY. CD8A is detected in 0.556 of them, but 18 cells are too few to change the label.
A zero count does not prove that a cell lacks a gene. CD3D itself is detected in 0.876 of cluster 0, not in every cell, and the split defines the group without CD3D by a zero CD3D count, so that group can also hold T cells. The label “CD8 T and NK cells” rests on the contrast between the groups, CD8A at 0.085 in the GNLY cells without CD3D against 0.538 and 0.444 in the CD3D cells. About half of the CD3D cells show no CD8A count. They can be CD8 T cells whose CD8A count is zero, or other T cells that the sequencing depth of PBMC 3k cannot resolve.
# Cluster 2 holds CD8 T cells and NK cells. In the split above, CD8A# is detected in about half of its CD3D cells and is rare in its GNLY# cells without CD3D. On the clustering page, resolution 0.8 splits# the left group, which holds clusters 0 and 2, into four clusters.cluster_labels = { "0": "CD4 T cells", "1": "CD14+ Monocytes", "2": "CD8 T and NK cells", "3": "B cells", "4": "FCGR3A+ Monocytes",}
adata.obs["cell_type"] = adata.obs["leiden"].map(cluster_labels)print(adata.obs["cell_type"].value_counts())cell_typeCD4 T cells 1099CD14+ Monocytes 456CD8 T and NK cells 412B cells 315FCGR3A+ Monocytes 146Name: count, dtype: int64sc.pl.umap(adata, color="cell_type", show=False)plt.savefig("outputs/annotation_cell-types.png", dpi=150, bbox_inches="tight")plt.close()
The five labels cover all 2,428 cells, and cluster 2 keeps its mixed label.
Why annotation is hard to reproduce
Section titled “Why annotation is hard to reproduce”Two analysts who annotate the same dataset often assign different labels. Three causes account for most of the disagreement.
The labels depend on the clustering resolution. At a low resolution there may be one T cell cluster, and at a high resolution the same cells split into naive and memory CD4 cells, CD8 effector cells, regulatory T cells and more. The right level of detail depends on the biological question, so different analysts choose differently. On this page the CD8 T cells and the NK cells share cluster 2 at resolution 0.5 for the same reason.
Many markers are not exclusive to one cell type. CD4 marks T helper cells but is also expressed by some monocytes. FOXP3 marks regulatory T cells but can appear for a short time in activated conventional T cells.
Markers also move between contexts. A cell type can express different markers in different tissues, disease states or species, so markers validated in PBMCs may fail in tumor tissue.
Automated annotation
Section titled “Automated annotation”Several tools assign labels without a manual marker review. This page does not run one, but the table lists the common choices.
| Tool | Language | Approach |
|---|---|---|
| SingleR | R | Correlates expression profiles against a labeled reference dataset |
| CellTypist | Python | Machine learning models pre-trained on large cell atlases |
| scType | R | Scores cells against curated marker gene sets |
| Azimuth | R | Projects query data onto a reference UMAP and transfers labels |
A benchmark of 22 classification methods on 27 datasets found that accuracy fell for deep annotations with many small cell populations, and for predictions from one dataset to another, where technical and biological differences separate the reference from the query (Abdelaal et al. 2019, Genome Biology 20:194). SingleR was among the methods tested. CellTypist, scType and Azimuth came out later. Each tool is limited by its reference, so a model trained on healthy PBMCs can mislabel cells from a tumor microenvironment.
Good practice
Section titled “Good practice”Single-cell annotation has no gold standard. Bulk RNA-seq results can be checked by RT-qPCR, but no accepted ground truth exists for the label of a single cell. Five habits make a set of labels easier to trust and to reproduce.
- Use more than one annotation method and compare the results.
- Check automated labels against known marker genes.
- Report the annotation method and the reference dataset.
- Leave an ambiguous cluster unlabeled, or label it as mixed, as this page does for cluster 2.
- State the clustering resolution.
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”The Scanpy marker-test reference defines group comparisons, correction methods, and tie handling. It explains what the ranked marker statistics measure.
The scvi-tools API tutorial demonstrates marker inspection with dot plots. A marker display supports annotation but does not independently validate a cell identity.