Skip to content

Quality Control

Cell Ranger 1.1.0, the version that produced PBMC 3k, calls a barcode a cell from its UMI count alone, so some barcodes hold a dying cell, a nearly empty droplet or two cells. Cell Ranger 3.0 and later add a test that compares barcodes with few counts against the ambient RNA profile, in the manner of EmptyDrops, but a dying cell or a doublet can still pass it. This page measures three numbers per barcode on PBMC 3k and removes the outliers.

The table gives the Scanpy and the Seurat name of each metric.

Scanpy name Seurat name What it measures
total_counts nCount_RNA Total UMIs, the library size of the cell
n_genes_by_counts nFeature_RNA Genes with at least one count
pct_counts_mt percent.mt Share of counts from mitochondrial genes, high in dying cells

A fixed limit, such as a minimum of 200 genes per cell, does not move with the dataset. This page follows sc-best-practices and sets each limit from the data instead, as a number of median absolute deviations from the median.

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 np
import scanpy as sc
import matplotlib.pyplot as plt
sc.settings.verbosity = 3
sc.settings.set_figure_params(dpi=80, facecolor="white", frameon=False)
np.random.seed(42)
adata = sc.read_10x_mtx("/opt/data/pbmc3k", var_names="gene_symbols",
make_unique=True)
adata.layers["counts"] = adata.X.copy()
# Scanpy names the three metrics above total_counts, n_genes_by_counts
# and pct_counts_mt.
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)
print(adata.obs.head().to_string())
n_genes_by_counts total_counts total_counts_mt pct_counts_mt
AAACATACAACCAC-1 781 2421.0 73.0 3.015283
AAACATTGAGCTAC-1 1352 4903.0 186.0 3.793596
AAACATTGATCAGC-1 1131 3149.0 28.0 0.889171
AAACCGTGCTTCCG-1 960 2639.0 46.0 1.743085
AAACCGTGTATGCG-1 522 981.0 12.0 1.223242

Each row is one barcode. The first one has 2,421 UMIs over 781 genes, and 73 of its UMIs, 3.0 percent, come from mitochondrial genes.

sc.pl.violin(adata, ["n_genes_by_counts", "total_counts", "pct_counts_mt"],
multi_panel=True, jitter=0.4, size=1.5, show=False)
plt.savefig("outputs/quality-control_violin.png", dpi=150,
bbox_inches="tight")
plt.close()

Violin plots of the three QC metrics over all 2,700 cells before filtering. Gene counts per cell peak between 500 and 1,500, total counts peak between 2,000 and 5,000 UMI, and the mitochondrial fraction stays under 10 percent for most cells.

Most cells have 500 to 1,500 genes and fewer than 6,000 UMIs. The long upper tails hold a few cells with more than 2,500 genes or 10,000 UMIs, the profile of a possible doublet. The mitochondrial fraction stays under 5 percent for most cells, and a handful of cells pass 10 percent.

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
sc.pl.scatter(adata, x="total_counts", y="pct_counts_mt", ax=axes[0],
show=False)
sc.pl.scatter(adata, x="total_counts", y="n_genes_by_counts", ax=axes[1],
show=False)
plt.tight_layout()
plt.savefig("outputs/quality-control_scatter.png", dpi=150,
bbox_inches="tight")
plt.close()

Two QC scatter plots against total counts. The cells with the highest mitochondrial percentage, up to 22 percent, all have low total counts, and the spread narrows as the counts rise. Genes detected rise almost in a straight line with total counts.

The left panel shows the pattern of dying cells. All the cells with a high mitochondrial fraction have low total counts, because a broken cell loses its cytoplasmic mRNA while the transcripts inside the mitochondria stay. In the right panel genes and counts rise together, so a cell that is low on one metric is usually low on the other.

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.

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)
# sc-best-practices filters on median absolute deviations with lenient
# cutoffs, 5 MADs for the count metrics and 3 for the mitochondrial
# fraction, rather than on fixed thresholds.
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)
)
print(adata.obs["outlier"].value_counts())
outlier
False 2428
True 272
Name: count, dtype: int64

The rule flags 272 of the 2,700 cells, 10.1 percent of the dataset.

adata = adata[~adata.obs["outlier"]].copy()
print(f"{adata.n_obs} cells remain")
2428 cells remain

The 2,428 cells that remain are the starting point of every later page that works on PBMC 3k alone.

# Filter genes expressed in fewer than 3 cells. sc-best-practices
# reports no clear downstream benefit from gene filtering, but it
# shrinks the matrix.
n_genes_before = adata.n_vars
sc.pp.filter_genes(adata, min_cells=3)
print(f"genes before the filter: {n_genes_before}")
print(f"genes removed: {n_genes_before - adata.n_vars}")
print(adata.shape)
genes before the filter: 32738
genes removed: 19264
(2428, 13474)

The gene filter removes 19,264 of the 32,738 genes, the genes found in fewer than 3 cells, and keeps 13,474.

Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.

The Single-cell best practices QC chapter explains count, feature, and mitochondrial quality metrics. Its current filtering choices differ from the archived helper credited above.

The 10x Genomics PBMC 3k record identifies the Cell Ranger 1.1.0 dataset and its reuse terms. It fixes the source of the matrix used for these QC calculations.