Human shotgun cohort statistics
A group comparison needs an independent analysis unit and a stated outcome. This lesson uses one archived stool sample per participant, selected before examining diversity. Shannon diversity is the alpha diversity outcome, and Aitchison distance describes the bacterial and archaeal species composition.
The cohort selection removes repeated participants and the extreme low depth sample. The profiler comparison explains why this lesson uses Bracken estimates without converting MetaPhlAn percentages into artificial counts. These are estimated fragments, not directly observed cell counts.
Separate the statistical questions
Section titled “Separate the statistical questions”Shannon diversity uses all retained bacterial and archaeal Bracken species, with natural logarithms. Reported species richness counts positive estimates and remains descriptive because sequencing effort and classification errors affect it. The depth plot exposes unequal effort instead of assuming that relative abundance normalization removes it.
The Kruskal-Wallis test asks whether the three groups have the same rank distribution of Shannon diversity. Its p-value does not identify a specific pair or establish a median difference unless distribution shapes are comparable. Three two sided Mann-Whitney comparisons use the asymptotic approximation, continuity correction, and Holm adjustment within that family of three tests.
For community composition, retain species with at least ten estimated fragments in at least 20 percent of participants. Add 0.5 to those counts and take the centered log ratio. Euclidean distance between those coordinates is Aitchison distance for this specified replacement. The count pseudocount interacts with depth, so this choice requires sensitivity analysis in a substantive study.
PERMANOVA tests the association between diagnosis and that distance matrix. Its R squared describes the fraction of distance variation attributed to the group term. A separate PERMDISP diagnostic tests group dispersion around spatial medians. Unequal dispersion can complicate a location interpretation, especially when group sizes differ. A large diagnostic p-value does not prove equal dispersion. See the vegan PERMANOVA documentation and dispersion documentation.
Run both analyses
Section titled “Run both analyses”Each test uses 999 permutations where applicable and seed 137. Permutations are unrestricted across the selected participants. This requires exchangeable participants under the null; removing repeated samples alone does not resolve confounding by collection site or treatment.
R and Python use different random number generators. Their permutation p-values can differ, and their dispersion procedures also differ: vegan permutes model residuals, while scikit-bio permutes group labels and recalculates group medians. The gate compares the observed statistics, Shannon tests, and explained variance, rather than requiring identical permutation p-values. The scikit-bio PERMDISP documentation describes its implementation.
The Python call explicitly retains all ordination dimensions for PERMDISP. The installed scikit-bio release otherwise keeps ten, which changes the dispersion statistic. The spatial median solvers differ slightly in numerical tolerance, so the comparison allows an absolute F difference of 0.0001.
Both tabs run in the companion microbiome:0.1.0 container with the checked
IBDMDB fixtures. The cohort page
provides access instructions and provenance.
The archived read analyses use 30 public runs from the Lloyd-Price and colleagues IBDMDB study, covered by the INSDC data policy. The original iHMP data-use policy also permits use of the clinical metadata; its publication moratorium ended by fall 2018. These data were supplied by Ramnik Xavier and Curtis Huttenhower through the HMP program with NIH Common Fund grant 8U54DK102557.
library(ggplot2)library(jsonlite)
metadata <- read.delim("/fixtures/ibdmdb_metadata.tsv", row.names = 1, check.names = FALSE)metadata <- metadata[metadata$selected == "True", ]counts <- t(as.matrix(read.delim("/fixtures/ibdmdb_bracken_counts.tsv", row.names = 1, check.names = FALSE)))counts <- counts[rownames(metadata), , drop = FALSE]stopifnot(identical(rownames(counts), rownames(metadata)))stopifnot(!anyDuplicated(metadata$subject_id), all(rowSums(counts) > 0))groups <- c("nonIBD", "CD", "UC")metadata$diagnosis <- factor(metadata$diagnosis, levels = groups)dir.create("outputs", showWarnings = FALSE)
library(vegan)
shannon <- diversity(counts, index = "shannon")richness <- rowSums(counts > 0)for (group in groups) { selected <- metadata$diagnosis == group cat(sprintf("%s median Shannon: %.6f; median reported species: %.1f\n", group, median(shannon[selected]), median(richness[selected])))}omnibus <- kruskal.test(shannon ~ metadata$diagnosis)cat(sprintf("Shannon omnibus H: %.6f; p: %.6f\n", omnibus$statistic, omnibus$p.value))pairs <- combn(groups, 2)raw_p <- numeric(ncol(pairs))for (i in seq_len(ncol(pairs))) { first <- shannon[metadata$diagnosis == pairs[1, i]] second <- shannon[metadata$diagnosis == pairs[2, i]] raw_p[i] <- wilcox.test(first, second, exact = FALSE, correct = TRUE)$p.value}adjusted_p <- p.adjust(raw_p, method = "holm")for (i in seq_len(ncol(pairs))) { cat(sprintf("Shannon %s vs %s: raw p=%.6f; Holm p=%.6f\n", pairs[1, i], pairs[2, i], raw_p[i], adjusted_p[i]))}keep <- colSums(counts >= 10) >= ceiling(0.2 * nrow(counts))log_counts <- log(counts[, keep, drop = FALSE] + 0.5)clr <- log_counts - rowMeans(log_counts)distance <- dist(clr)set.seed(137)permanova <- adonis2(distance ~ diagnosis, data = metadata, permutations = 999)dispersion <- betadisper(distance, metadata$diagnosis, type = "median")set.seed(137)dispersion_test <- permutest(dispersion, permutations = 999)cat(sprintf("Species retained for CLR: %d\n", sum(keep)))cat(sprintf("PERMANOVA F: %.6f; R2: %.6f; p: %.3f\n", permanova$F[1], permanova$R2[1], permanova$`Pr(>F)`[1]))cat(sprintf("PERMDISP F: %.6f; p: %.3f\n", dispersion_test$tab$F[1], dispersion_test$tab$`Pr(>F)`[1]))ordination <- prcomp(clr, center = TRUE, scale. = FALSE)explained <- ordination$sdev^2 / sum(ordination$sdev^2)plot_data <- data.frame(metadata, shannon = shannon, richness = richness, pc1 = ordination$x[, 1], pc2 = ordination$x[, 2])colors <- c("#287d8e", "#c95d35", "#8462ab")alpha_figure <- ggplot(plot_data, aes(bracken_microbe_fragments, shannon, color = diagnosis)) + geom_point(size = 2.7) + scale_x_log10() + scale_color_manual(values = colors) + theme_bw(base_size = 11) + labs(x = "Bracken bacterial and archaeal fragments", y = "Shannon diversity, natural log", color = "Diagnosis")ggsave("outputs/shotgun_shannon_r.png", alpha_figure, width = 7, height = 4.5, dpi = 160)beta_figure <- ggplot(plot_data, aes(pc1, pc2, color = diagnosis)) + geom_point(size = 2.7) + coord_equal() + scale_color_manual(values = colors) + theme_bw(base_size = 11) + labs(x = sprintf("PC1 (%.1f%%)", 100 * explained[1]), y = sprintf("PC2 (%.1f%%)", 100 * explained[2]), color = "Diagnosis")ggsave("outputs/shotgun_ordination_r.png", beta_figure, width = 7, height = 4.5, dpi = 160)write.table(plot_data, "outputs/sample_statistics_r.tsv", sep = "\t", row.names = TRUE, quote = FALSE)write_json(list(first_shannon = shannon[1], omnibus_p = omnibus$p.value, pair1_p = adjusted_p[1], pair2_p = adjusted_p[2], pair3_p = adjusted_p[3], retained = sum(keep), permanova_f = permanova$F[1], r2 = permanova$R2[1], dispersion_f = dispersion_test$tab$F[1], pc1 = explained[1], pc2 = explained[2]), "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)nonIBD median Shannon: 2.025453; median reported species: 561.0CD median Shannon: 2.507037; median reported species: 388.0UC median Shannon: 2.476033; median reported species: 360.0Shannon omnibus H: 1.064577; p: 0.587259Shannon nonIBD vs CD: raw p=0.391267; Holm p=1.000000Shannon nonIBD vs UC: raw p=0.458719; Holm p=1.000000Shannon CD vs UC: raw p=0.732678; Holm p=1.000000Species retained for CLR: 509PERMANOVA F: 1.092864; R2: 0.086784; p: 0.242PERMDISP F: 1.366805; p: 0.291

import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import stats
metadata = pd.read_csv("/fixtures/ibdmdb_metadata.tsv", sep="\t", index_col=0, dtype={"selected": str})metadata = metadata.loc[metadata["selected"].eq("True")]counts = pd.read_csv("/fixtures/ibdmdb_bracken_counts.tsv", sep="\t", index_col=0).T.loc[metadata.index]assert counts.index.equals(metadata.index)assert metadata["subject_id"].is_uniqueassert (counts.sum(axis=1) > 0).all()groups = ["nonIBD", "CD", "UC"]output = Path("outputs")output.mkdir(exist_ok=True)
from itertools import combinations
from scipy.spatial.distance import pdist, squareformfrom skbio import DistanceMatrixfrom skbio.stats.distance import permanova, permdispfrom statsmodels.stats.multitest import multipletests
shannon = pd.Series(stats.entropy(counts.to_numpy(), axis=1), index=counts.index)richness = counts.gt(0).sum(axis=1)group_values = []for group in groups: selected = metadata["diagnosis"].eq(group) group_values.append(shannon.loc[selected].to_numpy()) print(f"{group} median Shannon: {shannon.loc[selected].median():.6f}; " f"median reported species: {richness.loc[selected].median():.1f}")omnibus = stats.kruskal(*group_values)print(f"Shannon omnibus H: {omnibus.statistic:.6f}; p: {omnibus.pvalue:.6f}")pairs = list(combinations(groups, 2))raw_p = []for first, second in pairs: result = stats.mannwhitneyu( shannon.loc[metadata["diagnosis"].eq(first)], shannon.loc[metadata["diagnosis"].eq(second)], alternative="two-sided", method="asymptotic", use_continuity=True ) raw_p.append(result.pvalue)adjusted_p = multipletests(raw_p, method="holm")[1]for (first, second), raw, adjusted in zip(pairs, raw_p, adjusted_p): print(f"Shannon {first} vs {second}: raw p={raw:.6f}; " f"Holm p={adjusted:.6f}")keep = counts.ge(10).sum(axis=0) >= np.ceil(0.2 * len(counts))log_counts = np.log(counts.loc[:, keep].to_numpy() + 0.5)clr = log_counts - log_counts.mean(axis=1, keepdims=True)distance = DistanceMatrix(squareform(pdist(clr)), ids=metadata.index)permanova_result = permanova(distance, metadata, column="diagnosis", permutations=999, seed=137)dispersion_result = permdisp(distance, metadata, column="diagnosis", test="median", permutations=999, seed=137, dimensions=len(metadata))f_value = float(permanova_result["test statistic"])group_df = len(groups) - 1residual_df = len(metadata) - len(groups)r_squared = f_value * group_df / (f_value * group_df + residual_df)print(f"Species retained for CLR: {keep.sum()}")print(f"PERMANOVA F: {f_value:.6f}; R2: {r_squared:.6f}; " f"p: {permanova_result['p-value']:.3f}")print(f"PERMDISP F: {dispersion_result['test statistic']:.6f}; " f"p: {dispersion_result['p-value']:.3f}")centered = clr - clr.mean(axis=0)left, singular, right = np.linalg.svd(centered, full_matrices=False)coordinates = left[:, :2] * singular[:2]explained = singular**2 / np.sum(singular**2)colors = ["#287d8e", "#c95d35", "#8462ab"]figure, axis = plt.subplots(figsize=(7, 4.5))for group, color in zip(groups, colors): selected = metadata["diagnosis"].eq(group) axis.scatter(metadata.loc[selected, "bracken_microbe_fragments"], shannon.loc[selected], label=group, color=color)axis.set(xscale="log", xlabel="Bracken bacterial and archaeal fragments", ylabel="Shannon diversity, natural log")axis.legend(title="Diagnosis")figure.tight_layout()figure.savefig(output / "shotgun_shannon_python.png", dpi=160)plt.close(figure)figure, axis = plt.subplots(figsize=(7, 4.5))for group, color in zip(groups, colors): selected = metadata["diagnosis"].eq(group).to_numpy() axis.scatter(coordinates[selected, 0], coordinates[selected, 1], label=group, color=color)axis.set(xlabel=f"PC1 ({100 * explained[0]:.1f}%)", ylabel=f"PC2 ({100 * explained[1]:.1f}%)", aspect="equal")axis.legend(title="Diagnosis")figure.tight_layout()figure.savefig(output / "shotgun_ordination_python.png", dpi=160)plt.close(figure)metadata.assign(shannon=shannon, richness=richness, pc1=coordinates[:, 0], pc2=coordinates[:, 1]).to_csv( output / "sample_statistics_python.tsv", sep="\t")metrics = {"first_shannon": shannon.iloc[0], "omnibus_p": omnibus.pvalue, "pair1_p": adjusted_p[0], "pair2_p": adjusted_p[1], "pair3_p": adjusted_p[2], "retained": int(keep.sum()), "permanova_f": f_value, "r2": r_squared, "dispersion_f": float(dispersion_result["test statistic"]), "pc1": explained[0], "pc2": explained[1]}(output / "metrics_python.json").write_text(json.dumps(metrics))nonIBD median Shannon: 2.025453; median reported species: 561.0CD median Shannon: 2.507037; median reported species: 388.0UC median Shannon: 2.476033; median reported species: 360.0Shannon omnibus H: 1.064577; p: 0.587259Shannon nonIBD vs CD: raw p=0.391267; Holm p=1.000000Shannon nonIBD vs UC: raw p=0.458719; Holm p=1.000000Shannon CD vs UC: raw p=0.732678; Holm p=1.000000Species retained for CLR: 509PERMANOVA F: 1.092864; R2: 0.086784; p: 0.224PERMDISP F: 1.366831; p: 0.277

Interpret an association within this subset
Section titled “Interpret an association within this subset”The displayed Shannon tests do not provide evidence of a diagnosis group difference at a 0.05 threshold. The community test also does not resolve a diagnosis association at that threshold. These results do not establish equal communities, particularly with few participants and unadjusted confounders.
The ordination shows the first two principal components of the CLR coordinates. It uses no diagnosis labels to fit the axes. R and Python may reverse an axis sign without changing distances, explained variance, or group relationships. Visual separation in this projection does not replace the full distance test.
The omnibus Shannon result and the three pairwise results answer different questions. Read the adjusted p-value for the named pair before attributing an omnibus result to UC versus nonIBD. No alpha diversity test here identifies a taxon responsible for the pattern.
These comparisons describe an archived teaching subset. They do not adjust for age, medication, collection site, disease activity, or sequencing depth. The analysis also fixes one database pair, one feature filter, and one zero replacement. A disease biomarker claim needs a prespecified target, sensitivity analyses, appropriate covariates, and validation in independent participants.
The differential abundance lesson uses a separate paired 16S dataset. Its discoveries cannot be transferred to this human shotgun cohort.
Scientific references
Section titled “Scientific references”The vegan package by Oksanen and colleagues supplies community ecology methods such as diversity indices, ordination, and PERMANOVA.
Aton and colleagues, 2025 describe scikit-bio, the Python library for biological omic data analysis.
Further reading
Section titled “Further reading”-
vegan multivariate test references
The adonis2 and betadisper manuals separate group location from dispersion and document restricted permutation inputs. These definitions limit an interpretation of the unadjusted diagnosis test.
-
The reference documents group alignment, centroid or median choices, and ordination dimensions. Compare these choices before interpreting agreement between the two dispersion statistics.
-
Gloor and colleagues, Microbiome Datasets Are Compositional
The paper connects CLR coordinates to Aitchison distance. The lesson declares its count replacement and retained feature set before using that distance.