Compositional data and zeros
A sequencing library reports a finite allocation of reads among features. Its total is not a measurement of microbial biomass. Doubling every organism in the sample can leave the observed proportions unchanged.
The centered log ratio, CLR, compares each component with the geometric mean of the included components. Its reference therefore changes when the feature set changes. A CLR difference must name that reference and its treatment of zeros.
Run this example
Section titled “Run this example”The example uses the prepared Kostic colorectal cohort. The workflow and dataset page explains its source, paired design, and selection rule. Counts, taxonomy, and metadata come from the same public archive. The original features are reference OTUs, not ASVs from the separate ampliseq demonstration.
The companion repository
is private and requires access. Its microbiome:0.1.0 container provides the
packages, and the runner mounts the prepared tables at /fixtures.
Run each language’s blocks in order. The container runs without network access.
Read the data and calculate the result
Section titled “Read the data and calculate the result”The example retains OTUs with at least five reads in ten percent of samples. It adds either 0.5 or one count before taking natural logarithms. These values are sensitivity choices, not estimates of unobserved organisms. The figure compares the resulting coordinates in the first sample.
The paired counts and metadata come from Kostic and colleagues, distributed in the pinned phyloseq example archive. McMurdie and Holmes distribute that package under AGPL-3. The source notice records the exact archive, the 76-subject selection, and the applicable package terms.
library(ggplot2)library(jsonlite)
counts <- read.delim( "/fixtures/cohort_counts.tsv", row.names = 1, check.names = FALSE)counts <- t(as.matrix(counts))metadata <- read.delim("/fixtures/cohort_metadata.tsv")metadata <- metadata[match(rownames(counts), metadata$sample_id), ]stopifnot(identical(rownames(counts), metadata$sample_id))stopifnot(all(counts >= 0), all(counts == floor(counts)))dir.create("outputs", showWarnings = FALSE)
filtered <- counts[, colMeans(counts >= 5) >= 0.10, drop = FALSE]log_half <- log(filtered + 0.5)log_one <- log(filtered + 1)clr_half <- log_half - rowMeans(log_half)clr_one <- log_one - rowMeans(log_one)maximum_change <- max(abs(clr_half - clr_one))cat("Retained OTUs:", ncol(filtered), "\n")cat(sprintf("Largest absolute CLR change: %.6f\n", maximum_change))cat(sprintf("Largest absolute row mean: %.12f\n", max(abs(rowMeans(clr_one)))))plot_data <- data.frame(half = clr_half[1, ], one = clr_one[1, ])figure <- ggplot(plot_data, aes(half, one)) + geom_abline(slope = 1, intercept = 0, color = "gray60") + geom_point(alpha = 0.6, color = "#286b8f") + theme_minimal(base_size = 12) + labs(x = "CLR with 0.5 added", y = "CLR with 1 added")ggsave("outputs/compositional_data_r.png", figure, width = 5, height = 4, dpi = 160)write_json(list(features = ncol(filtered), maximum_change = maximum_change, first_clr = clr_one[1, 1]), "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)Retained OTUs: 194Largest absolute CLR change: 0.629443Largest absolute row mean: 0.000000000000
import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import statsfrom scipy.spatial.distance import pdist, squareform
counts = pd.read_csv( "/fixtures/cohort_counts.tsv", sep="\t", index_col=0).Tmetadata = pd.read_csv( "/fixtures/cohort_metadata.tsv", sep="\t", index_col=0).loc[counts.index]assert counts.index.equals(metadata.index)assert (counts.to_numpy() >= 0).all()assert (counts.to_numpy() == np.floor(counts.to_numpy())).all()output = Path("outputs")output.mkdir(exist_ok=True)
from skbio.stats.composition import clr
filtered = counts.loc[:, (counts >= 5).mean(axis=0) >= 0.10]clr_half = clr(filtered.to_numpy() + 0.5)clr_one = clr(filtered.to_numpy() + 1)maximum_change = np.abs(clr_half - clr_one).max()print(f"Retained OTUs: {filtered.shape[1]}")print(f"Largest absolute CLR change: {maximum_change:.6f}")print(f"Largest absolute row mean: {np.abs(clr_one.mean(axis=1)).max():.12f}")figure, axis = plt.subplots(figsize=(5, 4))limits = [min(clr_half[0].min(), clr_one[0].min()), max(clr_half[0].max(), clr_one[0].max())]axis.plot(limits, limits, color="gray")axis.scatter(clr_half[0], clr_one[0], alpha=0.6, color="#286b8f")axis.set(xlabel="CLR with 0.5 added", ylabel="CLR with 1 added")figure.tight_layout()figure.savefig(output / "compositional_data_python.png", dpi=160)plt.close(figure)metrics = {"features": filtered.shape[1], "maximum_change": float(maximum_change), "first_clr": float(clr_one[0, 0])}(output / "metrics_python.json").write_text(json.dumps(metrics))Retained OTUs: 194Largest absolute CLR change: 0.629443Largest absolute row mean: 0.000000000000
Distinguish absence from non-detection
Section titled “Distinguish absence from non-detection”A zero can reflect an organism that was absent, an organism missed at the available depth, or a sequence the database could not classify. A pseudocount does not distinguish those causes. Its effect is largest for small counts and depends on sequencing depth.
The compositional data discussion by Gloor and colleagues explains why proportions alone cannot recover absolute abundance. External measurements, such as a suitable spike-in or a microbial load assay, address a different measurement problem. Their own calibration and recovery assumptions still require attention.
Use the same feature set and zero rule when comparing samples. Report sensitivity when the scientific interpretation changes with that rule.
Scientific references
Section titled “Scientific references”Aton and colleagues, 2025 describe scikit-bio, the Python library for biological omic data analysis.
Further reading
Section titled “Further reading”-
Gloor and colleagues, Microbiome Datasets Are Compositional
The paper defines the geometric mean reference in CLR coordinates and explains why relative measurements cannot recover absolute abundance. Its discussion distinguishes zero replacement from observation.
-
The reference specifies positive input values and the axis of transformation. The two count additions in this lesson therefore remain explicit choices before the same transformation.