Visualize the paired comparison
A figure should preserve the design that produced the estimate. A boxplot of normal and tumor tissues hides which observations belong to the same patient. A paired display exposes that connection and makes disagreement between patients visible.
This example uses the log ratio of Fusobacterium counts to Bacteroides counts. The two genera define a direct reference comparison. Neither is a guaranteed stable denominator, and their names do not turn a ratio into an absolute load.
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 aggregates all OTUs assigned to each named genus and adds one count to each total before taking a natural log ratio. It plots every patient pair. The mean difference is descriptive here; the example does not perform an additional hypothesis test after selecting these genera from prior knowledge.
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)
taxonomy <- read.delim("/fixtures/cohort_taxonomy.tsv")taxonomy <- taxonomy[match(colnames(counts), taxonomy$feature_id), ]fusobacterium <- rowSums(counts[, taxonomy$genus == "g__Fusobacterium", drop = FALSE])bacteroides <- rowSums(counts[, taxonomy$genus == "g__Bacteroides", drop = FALSE])log_ratio <- log((fusobacterium + 1) / (bacteroides + 1))plot_data <- data.frame(subject = metadata$subject_id, tissue = metadata$tissue, log_ratio = log_ratio)figure <- ggplot(plot_data, aes(tissue, log_ratio, group = subject)) + geom_line(alpha = 0.25, color = "gray50") + geom_point(aes(color = tissue), alpha = 0.7) + theme_minimal(base_size = 12) + labs(x = "Tissue", y = "ln[(Fusobacterium + 1) / (Bacteroides + 1)]", color = "Tissue")ggsave("outputs/visualization_r.png", figure, width = 6, height = 5, dpi = 160)normal <- metadata$tissue == "normal"tumor <- metadata$tissue == "tumor"stopifnot(identical(metadata$subject_id[normal], metadata$subject_id[tumor]))mean_change <- mean(log_ratio[tumor] - log_ratio[normal])cat(sprintf("Mean paired log ratio change: %.6f\n", mean_change))cat("Samples without detected Fusobacterium:", sum(fusobacterium == 0), "\n")write_json(list(mean_change = mean_change, undetected = sum(fusobacterium == 0)), "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)Mean paired log ratio change: 1.848965Samples without detected Fusobacterium: 8
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)
taxonomy = pd.read_csv( "/fixtures/cohort_taxonomy.tsv", sep="\t", index_col=0, dtype=str)taxonomy.index = taxonomy.index.astype(str)counts.columns = counts.columns.astype(str)taxonomy = taxonomy.loc[counts.columns]fusobacterium = counts.loc[ :, taxonomy["genus"] == "g__Fusobacterium"].sum(axis=1)bacteroides = counts.loc[:, taxonomy["genus"] == "g__Bacteroides"].sum(axis=1)log_ratio = np.log((fusobacterium + 1) / (bacteroides + 1))normal = metadata["tissue"] == "normal"tumor = metadata["tissue"] == "tumor"assert np.array_equal(metadata.loc[normal, "subject_id"], metadata.loc[tumor, "subject_id"])figure, axis = plt.subplots(figsize=(6, 5))paired = np.column_stack([log_ratio[normal], log_ratio[tumor]])axis.plot([0, 1], paired.T, color="gray", alpha=0.25)axis.scatter(np.zeros(normal.sum()), log_ratio[normal], label="normal", alpha=0.7)axis.scatter(np.ones(tumor.sum()), log_ratio[tumor], label="tumor", alpha=0.7)axis.set_xticks([0, 1], ["normal", "tumor"])axis.set(xlabel="Tissue", ylabel="ln[(Fusobacterium + 1) / (Bacteroides + 1)]")figure.tight_layout()figure.savefig(output / "visualization_python.png", dpi=160)plt.close(figure)mean_change = float((paired[:, 1] - paired[:, 0]).mean())undetected = int((fusobacterium == 0).sum())print(f"Mean paired log ratio change: {mean_change:.6f}")print("Samples without detected Fusobacterium:", undetected)metrics = {"mean_change": mean_change, "undetected": undetected}(output / "metrics_python.json").write_text(json.dumps(metrics))Mean paired log ratio change: 1.848965Samples without detected Fusobacterium: 8
Keep the caption tied to the measurement
Section titled “Keep the caption tied to the measurement”Each line connects tissues from one patient. An upward line describes a larger Fusobacterium to Bacteroides ratio in that patient’s tumor sample. A flat or downward line remains part of the result and should not disappear from the plot.
Zeros make the one-count addition influential for some samples. Show that rule in the axis label and compare another justified rule before drawing a biological conclusion. A genus label also inherits the resolution and limitations of the original taxonomic database.
For a figure intended to support a population claim, report the model estimate and its interval beside the raw observations. Include the independent patient count, assay, feature definition, transformation, and comparison in the caption.
Further reading
Section titled “Further reading”-
Gloor and colleagues, Microbiome Datasets Are Compositional
The paper explains how a log ratio changes relative to its named reference. This supports an interpretation of the displayed genus ratio without treating either genus as an absolute microbial load.
-
Pinned phyloseq Kostic archive
The source mapping file retains patient and tissue identities beside the reference OTUs. Those identities determine which observations connect in the paired display.