Differential Cell Abundance
A larger monocyte fraction does not tell you whether a tissue gained monocytes. The fraction can rise because monocytes increased, another population decreased, or the experiment recovered the populations differently. Differential cell abundance starts with a measurement and a denominator, then asks how that measurement differs across biological samples.
This lesson begins after quality control and cell annotation. It compares an invented paired experiment in R and Python. The analysis describes all captured cell fractions, then estimates changes in three cell ratios against a prespecified T-cell reference. Each donor contributes one difference to each comparison.
Define the comparison before counting cells
Section titled “Define the comparison before counting cells”The simulated experiment contains one control aliquot and one treated aliquot from each donor. Retained singlets receive one of six mutually exclusive labels. The labels include Unassigned, because dropping those cells would change the denominator whenever annotation succeeds at a different rate. The label pDC denotes plasmacytoid dendritic cells.
The descriptive fraction is the number of cells with a label divided by all retained cells in that sample. The inferential quantity is different: the treated-to-control change in the ratio of a target population to T cells. The three targets are B cells, NK cells, and monocytes. T cells are the reference, and pDCs remain descriptive because their simulated counts are sparse.
The reference is part of the analysis plan. In this simulation, treatment changes only the latent monocyte weight before the weights become capture probabilities. The T-cell weight is unchanged by construction. In a real experiment, a stable reference needs evidence from the biology or a separate measurement; the count table cannot prove it. Without that evidence, the result still describes a target-to-reference ratio, but it cannot attribute the change to the target alone.
Twenty donors give twenty independent pairs. Thousands of cells within one aliquot refine its measured composition; they do not create thousands of independent treatment assignments. The pseudobulk lesson uses the same distinction for gene expression.
Read the sample table and counts
Section titled “Read the sample table and counts”Download cell_abundance_samples.csv and cell_abundance_counts.csv into your working directory. Both files contain simulated data, and no donor is a real person. The sample table records the retained total independently of the count table. The count table has one row for every sample and label, including observed zeros.
The simulation source varies donor composition and capture depth before it draws cell counts. It records the latent reference ratios separately from the observed counts, so the known intervention does not enter the fitted model.
For your own data, count each retained cell barcode once within its sample and annotation. A zero means that an assayed sample contains no retained cell with that label. An absent sample, a failed library, or an unmeasured population must not become a zero row. These checks require the complete sample-by-label grid before a matrix operation can fill absent entries silently.
library(ggplot2)library(jsonlite)
samples <- read.csv("cell_abundance_samples.csv")counts <- read.csv("cell_abundance_counts.csv")cell_types <- c("T_cells", "B_cells", "NK_cells", "Monocytes", "pDC", "Unassigned")conditions <- c("Control", "Treated")stopifnot(!anyNA(samples), !anyNA(counts))stopifnot(!anyDuplicated(samples$sample_id))stopifnot(!anyDuplicated(samples[c("donor_id", "condition")]))stopifnot(setequal(samples$condition, conditions))stopifnot(all(table(samples$donor_id, samples$condition) == 1))stopifnot(all(samples$retained_cells > 0))keys <- paste(counts$sample_id, counts$cell_type, sep = "|")expected <- as.vector(outer(samples$sample_id, cell_types, paste, sep = "|"))stopifnot(!anyDuplicated(keys), setequal(keys, expected))stopifnot(all(counts$cell_count >= 0))stopifnot(all(counts$cell_count == floor(counts$cell_count)))count_matrix <- xtabs(cell_count ~ sample_id + cell_type, data = counts)count_matrix <- count_matrix[samples$sample_id, cell_types]stopifnot(all(rowSums(count_matrix) == samples$retained_cells))dir.create("outputs", showWarnings = FALSE)cat(sprintf("%d donors, %d samples, %d population rows\n", length(unique(samples$donor_id)), nrow(samples), nrow(counts)))cat(sprintf("Retained cells per sample: %d to %d\n", min(samples$retained_cells), max(samples$retained_cells)))cat(sprintf("Observed pDC zeros: %d samples\n", sum(count_matrix[, "pDC"] == 0)))20 donors, 40 samples, 240 population rowsRetained cells per sample: 741 to 4419Observed pDC zeros: 31 samplesimport jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import statsfrom statsmodels.stats.multitest import multipletests
samples = pd.read_csv("cell_abundance_samples.csv")counts = pd.read_csv("cell_abundance_counts.csv")cell_types = ["T_cells", "B_cells", "NK_cells", "Monocytes", "pDC", "Unassigned"]conditions = ["Control", "Treated"]assert not samples.isna().any().any()assert not counts.isna().any().any()assert samples["sample_id"].is_uniqueassert not samples.duplicated(["donor_id", "condition"]).any()assert samples["condition"].isin(conditions).all()pair_counts = pd.crosstab(samples["donor_id"], samples["condition"])assert set(pair_counts.columns) == set(conditions)assert pair_counts.eq(1).all().all()assert samples["retained_cells"].gt(0).all()keys = pd.MultiIndex.from_frame(counts[["sample_id", "cell_type"]])expected = pd.MultiIndex.from_product([samples["sample_id"], cell_types])assert keys.is_unique and set(keys) == set(expected)assert counts["cell_count"].ge(0).all()assert counts["cell_count"].eq(np.floor(counts["cell_count"])).all()count_matrix = counts.pivot(index="sample_id", columns="cell_type", values="cell_count")count_matrix = count_matrix.loc[samples["sample_id"], cell_types]assert np.array_equal(count_matrix.sum(axis=1), samples["retained_cells"])output = Path("outputs")output.mkdir(exist_ok=True)print(f"{samples['donor_id'].nunique()} donors, {len(samples)} samples, " f"{len(counts)} population rows")print(f"Retained cells per sample: {samples['retained_cells'].min()} to " f"{samples['retained_cells'].max()}")print(f"Observed pDC zeros: {count_matrix['pDC'].eq(0).sum()} samples")20 donors, 40 samples, 240 population rowsRetained cells per sample: 741 to 4419Observed pDC zeros: 31 samplesDescribe fractions with the same denominator
Section titled “Describe fractions with the same denominator”Every fraction uses all retained cells, including pDCs and unassigned cells. The sample totals vary, so pooling the counts would give more weight to donors with more captured cells. The table below instead averages each donor’s fraction with equal weight.
fractions <- sweep(count_matrix, 1, samples$retained_cells, "/")stopifnot(all(abs(rowSums(fractions) - 1) < 1e-12))fraction_summary <- data.frame( cell_type = cell_types, control_pct = 100 * colMeans(fractions[samples$condition == "Control", ]), treated_pct = 100 * colMeans(fractions[samples$condition == "Treated", ]))fraction_summary$change_pp <- fraction_summary$treated_pct - fraction_summary$control_pctprint(fraction_summary, digits = 4, row.names = FALSE)
long <- merge(counts, samples, by = "sample_id")long$percent <- 100 * long$cell_count / long$retained_cellslong$condition <- factor(long$condition, levels = conditions)long$cell_type <- factor(long$cell_type, levels = cell_types)fraction_plot <- ggplot(long, aes(condition, percent, group = donor_id)) + geom_line(color = "#85949a", alpha = 0.6) + geom_point(aes(color = condition), size = 1.5) + facet_wrap(~cell_type, scales = "free_y", ncol = 3) + scale_color_manual(values = c(Control = "#28536b", Treated = "#c36b38")) + labs(x = NULL, y = "Percent of all retained cells", title = "One line connects the two samples from one donor", subtitle = "The vertical scale differs between populations") + theme_bw(base_size = 11) + theme(legend.position = "none")ggsave("outputs/cell_abundance_fractions_r.png", fraction_plot, width = 11, height = 6.5, dpi = 150)write.csv(fraction_summary, "outputs/cell_abundance_fractions_r.csv", row.names = FALSE) cell_type control_pct treated_pct change_pp T_cells 49.82170 45.22190 -4.599799 B_cells 15.49471 14.38440 -1.110315 NK_cells 12.67421 11.33573 -1.338481 Monocytes 19.07498 26.29593 7.220946 pDC 0.01005 0.01643 0.006386 Unassigned 2.92434 2.74561 -0.178737
fractions = count_matrix.div(samples["retained_cells"].to_numpy(), axis=0)np.testing.assert_allclose(fractions.sum(axis=1), 1, atol=1e-12)control_rows = samples["condition"].eq("Control").to_numpy()treated_rows = samples["condition"].eq("Treated").to_numpy()fraction_summary = pd.DataFrame({ "cell_type": cell_types, "control_pct": 100 * fractions.loc[control_rows].mean().to_numpy(), "treated_pct": 100 * fractions.loc[treated_rows].mean().to_numpy(),})fraction_summary["change_pp"] = (fraction_summary["treated_pct"] - fraction_summary["control_pct"])print(fraction_summary.to_string(index=False, float_format="%.4f"))
long = counts.merge(samples, on="sample_id", validate="many_to_one")long["percent"] = 100 * long["cell_count"] / long["retained_cells"]figure, axes = plt.subplots(2, 3, figsize=(11, 6.5))for axis, cell_type in zip(axes.flat, cell_types): selected = long.loc[long["cell_type"].eq(cell_type)] paired = selected.pivot(index="donor_id", columns="condition", values="percent").loc[:, conditions] for values in paired.to_numpy(): axis.plot([0, 1], values, color="#85949a", alpha=0.6, linewidth=0.8) axis.scatter(np.zeros(len(paired)), paired["Control"], color="#28536b", s=12, zorder=3) axis.scatter(np.ones(len(paired)), paired["Treated"], color="#c36b38", s=12, zorder=3) axis.set(xticks=[0, 1], xticklabels=conditions, title=cell_type, ylabel="Percent of all retained cells")figure.suptitle("One line connects the two samples from one donor\n" "The vertical scale differs between populations")figure.tight_layout()figure.savefig(output / "cell_abundance_fractions_python.png", dpi=150)plt.close(figure)fraction_summary.to_csv(output / "cell_abundance_fractions_python.csv", index=False) cell_type control_pct treated_pct change_pp T_cells 49.8217 45.2219 -4.5998 B_cells 15.4947 14.3844 -1.1103 NK_cells 12.6742 11.3357 -1.3385 Monocytes 19.0750 26.2959 7.2209 pDC 0.0100 0.0164 0.0064Unassigned 2.9243 2.7456 -0.1787
The monocyte fraction rises while several other fractions fall. That pattern is expected when the simulation increases only the monocyte weight and then divides every weight by their new sum. A negative percentage point change in another population does not establish that its absolute cell number fell.
Unassigned cells remain visible for another reason. If treatment changes marker expression, a classification method can move cells between labels without any population expanding. Inspect the annotation and recovery process before giving a biological explanation to a composition change.
Choose a ratio that answers the question
Section titled “Choose a ratio that answers the question”For target population k in donor d, calculate the log2 target-to-T-cell ratio in each sample. Subtract control from treated. The result is the log2 of a ratio of ratios; the total captured count cancels within each sample.
The analysis fixes B cells, NK cells, and monocytes as one family of three comparisons. All four populations needed for these ratios have positive counts in every simulated sample. The code stops if that requirement fails. It does not add a pseudocount to make a zero disappear, and it does not remove a donor after inspecting the direction of the change.
targets <- c("B_cells", "NK_cells", "Monocytes")reference <- "T_cells"stopifnot(all(count_matrix[, c(reference, targets)] > 0))log_ratios <- log2(sweep(count_matrix[, targets], 1, count_matrix[, reference], "/"))donors <- sort(unique(samples$donor_id))control_ids <- samples$sample_id[samples$condition == "Control"]control_donors <- samples$donor_id[samples$condition == "Control"]treated_ids <- samples$sample_id[samples$condition == "Treated"]treated_donors <- samples$donor_id[samples$condition == "Treated"]control_ids <- control_ids[match(donors, control_donors)]treated_ids <- treated_ids[match(donors, treated_donors)]changes <- log_ratios[treated_ids, ] - log_ratios[control_ids, ]rownames(changes) <- donorsprint(round(head(changes, 4), 4))cat(sprintf("Independent paired differences per target: %d\n", nrow(changes))) cell_typesample_id B_cells NK_cells Monocytes D01 0.3116 0.0147 0.4960 D02 -0.0983 -0.0994 0.6070 D03 -0.0454 -0.0899 0.5277 D04 0.3319 0.1624 0.2096Independent paired differences per target: 20targets = ["B_cells", "NK_cells", "Monocytes"]reference = "T_cells"assert count_matrix[[reference, *targets]].gt(0).all().all()log_ratios = np.log2(count_matrix[targets].div(count_matrix[reference], axis=0))sample_pairs = samples.pivot(index="donor_id", columns="condition", values="sample_id").sort_index()control_ratios = log_ratios.loc[sample_pairs["Control"]].to_numpy()treated_ratios = log_ratios.loc[sample_pairs["Treated"]].to_numpy()changes = pd.DataFrame(treated_ratios - control_ratios, index=sample_pairs.index, columns=targets)print(changes.head(4).to_string(float_format="%.4f"))print(f"Independent paired differences per target: {len(changes)}") B_cells NK_cells Monocytesdonor_idD01 0.3116 0.0147 0.4960D02 -0.0983 -0.0994 0.6070D03 -0.0454 -0.0899 0.5277D04 0.3319 0.1624 0.2096Independent paired differences per target: 20A positive value means that the target-to-T-cell ratio is larger in the treated sample. It does not mean that the target gained that many cells. A change of one on this scale means that the ratio doubled, whether the target doubled, the reference halved, or both populations changed together.
Estimate the paired effect and its uncertainty
Section titled “Estimate the paired effect and its uncertainty”The model estimates the mean log2 ratio change across donors. A paired t-test is a one-sample t-test on those donor differences. Its interval assumes independent donors and approximately normal differences; a large number of captured cells cannot repair a poor donor-level model. Inspect the paired values and the difference distribution before using this model on another experiment.
The exponentiated mean is a geometric mean fold change in the target-to-reference ratio. Each donor has equal weight. It is neither a fold change in absolute cell number nor the ratio obtained by pooling cells across donors.
results <- data.frame(cell_type = targets, donors = nrow(changes), mean_log2 = NA_real_, low_log2 = NA_real_, high_log2 = NA_real_, p_value = NA_real_)for (i in seq_along(targets)) { test <- t.test(changes[, targets[i]], mu = 0) results$mean_log2[i] <- mean(changes[, targets[i]]) results$low_log2[i] <- test$conf.int[1] results$high_log2[i] <- test$conf.int[2] results$p_value[i] <- test$p.value}results$p_holm <- p.adjust(results$p_value, method = "holm")results$ratio_fold <- 2^results$mean_log2results$fold_low <- 2^results$low_log2results$fold_high <- 2^results$high_log2shown <- results[c("cell_type", "donors", "ratio_fold", "fold_low", "fold_high", "p_value", "p_holm")]print(shown, digits = 4, row.names = FALSE)write.csv(results, "outputs/cell_abundance_results_r.csv", row.names = FALSE)
summary_values <- list(donors = nrow(changes), tested_targets = nrow(results))for (i in seq_along(targets)) { prefix <- targets[i] summary_values[[paste0(prefix, "_mean_log2")]] <- results$mean_log2[i] summary_values[[paste0(prefix, "_low_log2")]] <- results$low_log2[i] summary_values[[paste0(prefix, "_high_log2")]] <- results$high_log2[i] summary_values[[paste0(prefix, "_p_holm")]] <- results$p_holm[i]}write_json(summary_values, "outputs/cell_abundance_summary_r.json", auto_unbox = TRUE, digits = 15, pretty = TRUE) cell_type donors ratio_fold fold_low fold_high p_value p_holm B_cells 20 1.024 0.9737 1.077 3.384e-01 6.768e-01 NK_cells 20 0.993 0.9523 1.035 7.272e-01 7.272e-01 Monocytes 20 1.528 1.4237 1.639 1.163e-10 3.489e-10rows = []for cell_type in targets: difference = changes[cell_type].to_numpy() test = stats.ttest_1samp(difference, popmean=0) interval = test.confidence_interval(0.95) rows.append({"cell_type": cell_type, "donors": len(difference), "mean_log2": difference.mean(), "low_log2": interval.low, "high_log2": interval.high, "p_value": test.pvalue})results = pd.DataFrame(rows)results["p_holm"] = multipletests(results["p_value"], method="holm")[1]results["ratio_fold"] = np.exp2(results["mean_log2"])results["fold_low"] = np.exp2(results["low_log2"])results["fold_high"] = np.exp2(results["high_log2"])shown = results[["cell_type", "donors", "ratio_fold", "fold_low", "fold_high", "p_value", "p_holm"]]print(shown.to_string(index=False, float_format="%.4g"))results.to_csv(output / "cell_abundance_results_python.csv", index=False)
summary_values = {"donors": len(changes), "tested_targets": len(results)}for row in results.itertuples(index=False): prefix = row.cell_type summary_values[f"{prefix}_mean_log2"] = row.mean_log2 summary_values[f"{prefix}_low_log2"] = row.low_log2 summary_values[f"{prefix}_high_log2"] = row.high_log2 summary_values[f"{prefix}_p_holm"] = row.p_holm(output / "cell_abundance_summary_python.json").write_text( json.dumps(summary_values, indent=2) + "\n")cell_type donors ratio_fold fold_low fold_high p_value p_holm B_cells 20 1.024 0.9737 1.077 0.3384 0.6768 NK_cells 20 0.993 0.9523 1.035 0.7272 0.7272Monocytes 20 1.528 1.424 1.639 1.163e-10 3.489e-10Holm adjustment controls the chance of at least one false rejection across the three planned tests, provided each test supplies a valid p-value. It does not require independence among the tests. That matters here because every ratio shares the same reference population. The displayed intervals are ordinary pointwise 95% intervals; they do not provide simultaneous 95% coverage for the whole family.
The monocyte-to-T-cell ratio increases in the simulated experiment. The B-cell and NK-cell ratio intervals include no change, even though both raw fractions declined. The result follows the chosen denominator; it does not identify absolute losses in those populations.
The CSV keeps the estimates, intervals, and adjusted p-values together. The JSON contains named summaries for a report. Preserve the reference label and subtraction direction with these files, because a ratio without its denominator is ambiguous.
Show the effect beside the donor differences
Section titled “Show the effect beside the donor differences”The first panel keeps every donor difference visible. The second panel places the interval on the fold-change scale, where one means no average log ratio change. Both panels describe the same comparison.
plot_data <- data.frame( donor_id = rep(donors, times = length(targets)), cell_type = rep(targets, each = length(donors)), change_log2 = as.vector(changes))plot_data$cell_type <- factor(plot_data$cell_type, levels = targets)results$cell_type <- factor(results$cell_type, levels = targets)difference_plot <- ggplot(plot_data, aes(cell_type, change_log2)) + geom_hline(yintercept = 0, linetype = "dashed", color = "grey50") + geom_point(position = position_jitter(width = 0.12, height = 0, seed = 18), color = "#28536b", alpha = 0.8, size = 2) + labs(x = NULL, y = "Treated minus control log2 ratio", title = "Each point represents one donor") + theme_bw(base_size = 12)effect_plot <- ggplot(results, aes(cell_type, ratio_fold)) + geom_hline(yintercept = 1, linetype = "dashed", color = "grey50") + geom_errorbar(aes(ymin = fold_low, ymax = fold_high), width = 0.1, color = "#28536b") + geom_point(color = "#c36b38", size = 3) + scale_y_log10(breaks = c(1, 1.2, 1.4, 1.6)) + labs(x = NULL, y = "Fold change in target / T-cell ratio", title = "Geometric mean and pointwise 95% interval") + theme_bw(base_size = 12)ggsave("outputs/cell_abundance_differences_r.png", difference_plot, width = 7, height = 4.5, dpi = 150)ggsave("outputs/cell_abundance_effects_r.png", effect_plot, width = 7, height = 4.5, dpi = 150)

rng = np.random.default_rng(18)figure, axis = plt.subplots(figsize=(7, 4.5))for position, cell_type in enumerate(targets): jitter = rng.uniform(-0.12, 0.12, len(changes)) axis.scatter(position + jitter, changes[cell_type], color="#28536b", alpha=0.8, s=25)axis.axhline(0, color="grey", linestyle="--", linewidth=1)axis.set(xticks=range(len(targets)), xticklabels=targets, ylabel="Treated minus control log2 ratio", title="Each point represents one donor")figure.tight_layout()figure.savefig(output / "cell_abundance_differences_python.png", dpi=150)plt.close(figure)
figure, axis = plt.subplots(figsize=(7, 4.5))errors = np.vstack([results["ratio_fold"] - results["fold_low"], results["fold_high"] - results["ratio_fold"]])axis.errorbar(range(len(targets)), results["ratio_fold"], yerr=errors, fmt="o", color="#c36b38", ecolor="#28536b", capsize=4)axis.axhline(1, color="grey", linestyle="--", linewidth=1)axis.set(xticks=range(len(targets)), xticklabels=targets, yscale="log", ylabel="Fold change in target / T-cell ratio", title="Geometric mean and pointwise 95% interval")axis.set_yticks([1, 1.2, 1.4, 1.6], labels=["1.0", "1.2", "1.4", "1.6"])axis.minorticks_off()figure.tight_layout()figure.savefig(output / "cell_abundance_effects_python.png", dpi=150)plt.close(figure)

Match another experiment to its design
Section titled “Match another experiment to its design”This example estimates a paired relative change among captured and annotated cells. The following changes require a different analysis decision.
| Your experiment | Required decision |
|---|---|
| Different donors supply the two conditions. | Use an independent-sample model; do not pair donors by row order. |
| A donor supplies several technical libraries for one biological sample. | Combine the technical counts after checking compatible protocols, or model their shared donor explicitly. |
| Age, batch, or another covariate differs between groups. | Use a design matrix that estimates the condition effect with the required covariates. A paired subtraction cannot remove a condition-confounded batch. |
| A target or reference has zero captured cells. | Retain the zero in the count table. Choose a count model that represents the sampling process, or keep that comparison descriptive. |
| A rare population is the primary endpoint. | Plan the required donors and capture depth for that population. Do not discard it because this example excludes sparse pDCs. |
| No reference population has a defensible interpretation. | Consider a joint compositional model and state its identifying assumptions. A data-selected reference does not become biologically stable because the model selected it. |
| The question concerns absolute tissue abundance. | Add a compatible absolute measurement, such as counts per measured tissue volume. Captured proportions alone cannot answer that question. |
For many populations, propeller models transformed sample proportions and shares information about their variances. scCODA models the count composition jointly with an explicit reference. Their models answer different questions from this three-ratio example, and their design requirements need to match the experiment. Neither method makes cells from one donor independent biological replicates.
Scientific references
Section titled “Scientific references”Holm, 1979 describes the sequential multiple-test procedure used to control family-wise error across the three planned comparisons.
Phipson and colleagues, 2022 describe propeller, which tests differences in cell type proportions with biological replication and variance moderation.
Büttner and colleagues, 2021 describe scCODA and the reference assumptions needed for a joint analysis of cell composition.
Further reading
Section titled “Further reading”The R t-test documentation and SciPy one-sample t-test documentation define the test and confidence interval applied to the donor differences. Read the paired-test lesson before changing the experimental unit or subtraction direction.
The R p.adjust documentation explains Holm correction and its control of family-wise error. It also distinguishes that goal from false discovery rate control.
The speckle documentation provides propeller methods for sample-level proportions. Its design matrices are useful when a comparison needs more than a paired subtraction.
The scCODA introduction explains joint composition analysis and reference selection. Compare its model assumptions with the three prespecified ratios here before substituting one analysis for the other.