Skip to content

Beta diversity and ordination

Beta diversity compares communities between samples. A distance definition decides which differences receive weight. Bray-Curtis on proportions emphasizes abundant components, while Aitchison distance measures Euclidean separation between log ratio coordinates.

An ordination draws a low dimensional representation of those relationships. Visible separation is not a statistical test, and an overlapping plot does not prove that a modeled tissue effect is absent.

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.

Both languages compute Bray-Curtis on sample proportions and Aitchison distance after the same prevalence filter and one-count pseudocount. The plot uses principal components of the CLR table, so its geometry corresponds to Aitchison distance. The sign of an axis can reverse without changing distances.

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)
library(vegan)
relative <- counts / rowSums(counts)
bray <- as.matrix(vegdist(relative, method = "bray"))
filtered <- counts[, colMeans(counts >= 5) >= 0.10, drop = FALSE]
log_counts <- log(filtered + 1)
clr_counts <- log_counts - rowMeans(log_counts)
aitchison <- as.matrix(dist(clr_counts))
ordination <- prcomp(clr_counts, center = TRUE, scale. = FALSE)
explained <- ordination$sdev^2 / sum(ordination$sdev^2)
plot_data <- data.frame(pc1 = ordination$x[, 1], pc2 = ordination$x[, 2],
tissue = metadata$tissue)
figure <- ggplot(plot_data, aes(pc1, pc2, color = tissue)) +
geom_point(alpha = 0.65) + theme_minimal(base_size = 12) +
labs(x = "CLR principal component 1", y = "CLR principal component 2",
color = "Tissue")
ggsave("outputs/beta_diversity_r.png", figure, width = 6, height = 4, dpi = 160)
cat(sprintf("First pair Bray-Curtis: %.6f\n", bray[1, 2]))
cat(sprintf("First pair Aitchison: %.6f\n", aitchison[1, 2]))
cat(sprintf("Variance fraction in first two axes: %.6f\n", sum(explained[1:2])))
write_json(list(first_bray = bray[1, 2], first_aitchison = aitchison[1, 2],
first_two_axes = sum(explained[1:2])),
"outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)
First pair Bray-Curtis: 0.243954
First pair Aitchison: 7.187469
Variance fraction in first two axes: 0.164963

Beta diversity and ordination from the R example.

PERMANOVA partitions variation in a distance matrix according to a model. For these data, the model must account for patient identity, and a tissue-label permutation must respect the paired design. Unrestricted shuffles treat related tissues as exchangeable independent observations and answer a different question.

Use a design that includes patient and tissue, then test the tissue term with within-patient exchanges when the null hypothesis supports those exchanges. Report the distance, model, effect size, number of permutations, and restrictions. Repeated observations are not automatically exchangeable merely because they share a subject label; a time series can require a different permutation scheme.

Check multivariate dispersion as a separate diagnostic. Differences in dispersion can contribute to a PERMANOVA result, especially in unbalanced designs. A nonsignificant dispersion test does not prove equal dispersion. The vegan documentation describes adonis2 and its relationship to betadisper.

This additional R example includes patient as a fixed effect and tests the tissue term. It restricts 199 permutations within patients. This gives a minimum attainable Monte Carlo p-value of 0.005, so the example cannot resolve smaller tail probabilities. The exchangeability assumption is a property of the null model, not a consequence of the software accepting the block labels.

The dispersion diagnostic uses the same paired restriction. It examines a different property from the adjusted location comparison and should be read alongside the study design and ordination.

set.seed(104)
permutation_scheme <- permute::how(
nperm = 199, blocks = factor(metadata$subject_id)
)
permanova <- adonis2(
as.dist(bray) ~ subject_id + tissue, data = metadata,
permutations = permutation_scheme, by = "margin"
)
dispersion <- betadisper(as.dist(bray), factor(metadata$tissue))
dispersion_test <- permutest(dispersion, permutations = permutation_scheme)
cat(sprintf("Adjusted tissue pseudo-F: %.6f\n", permanova["tissue", "F"]))
cat(sprintf("Tissue R2 from the model: %.6f\n", permanova["tissue", "R2"]))
cat(sprintf("Restricted permutation p-value: %.6f\n",
permanova["tissue", "Pr(>F)"]))
cat(sprintf("Dispersion diagnostic p-value: %.6f\n",
dispersion_test$tab[1, "Pr(>F)"]))
Adjusted tissue pseudo-F: 9.744371
Tissue R2 from the model: 0.021574
Restricted permutation p-value: 0.005000
Dispersion diagnostic p-value: 0.005000

The Python example above covers the distances and ordination. This R model adds the patient adjustment and restricted permutations; its p-value is not an output of an unrestricted two-group Python PERMANOVA. The example interprets only the tissue term. Within-patient exchanges do not provide a test of the patient term.

The dispersion diagnostic also reaches the minimum p-value available from this permutation count. That result limits an interpretation based only on a centroid shift. Report the dispersion evidence with the tissue test, the effect size, and the paired observational design.

The vegan package by Oksanen and colleagues supplies community ecology methods such as diversity indices, ordination, and PERMANOVA.

  • vegan adonis2 reference

    The manual explains marginal model tests, restricted permutations, and the effect of dispersion on distance tests. These definitions support the patient adjustment and separate dispersion diagnostic.

  • Gloor and colleagues, Microbiome Datasets Are Compositional

    The paper defines Aitchison distance through CLR coordinates and discusses compositional ordination. The lesson specifies its own prevalence filter and zero rule before computing that geometry.