Alpha diversity
Alpha diversity describes variation within a sample. Observed richness counts detected features, while Shannon diversity also responds to their relative distribution. Neither quantity is a general score for a healthy microbiome.
This lesson uses the complete retained cohort table, without the prevalence filter used for the log ratio examples. Removing rare OTUs would change the richness target before it was measured.
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”Shannon diversity uses natural logarithms in both languages. The paired interval describes the mean tumor minus normal difference across patients. It uses the t distribution and assumes independent patient differences. It does not remove sequencing depth effects or establish a causal tissue effect.
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)
richness <- rowSums(counts > 0)shannon <- diversity(counts, index = "shannon")normal <- which(metadata$tissue == "normal")tumor <- which(metadata$tissue == "tumor")stopifnot(identical(metadata$subject_id[normal], metadata$subject_id[tumor]))difference <- shannon[tumor] - shannon[normal]interval <- t.test(difference)$conf.intcat(sprintf("Mean observed richness: %.3f\n", mean(richness)))cat(sprintf("Mean paired Shannon difference: %.6f\n", mean(difference)))cat(sprintf("95 percent interval: %.6f to %.6f\n", interval[1], interval[2]))plot_data <- data.frame(reads = rowSums(counts), shannon = shannon, tissue = metadata$tissue)figure <- ggplot(plot_data, aes(reads, shannon, color = tissue)) + geom_point(alpha = 0.65) + scale_x_log10() + theme_minimal(base_size = 12) + labs(x = "Reads per sample", y = "Shannon diversity, natural log", color = "Tissue")ggsave("outputs/alpha_diversity_r.png", figure, width = 6, height = 4, dpi = 160)write_json(list(first_shannon = shannon[1], mean_difference = mean(difference), lower = interval[1], upper = interval[2]), "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)Mean observed richness: 197.849Mean paired Shannon difference: -0.45497695 percent interval: -0.639768 to -0.270183
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.diversity import alpha_diversity
richness = (counts > 0).sum(axis=1)shannon = alpha_diversity("shannon", counts.to_numpy(), ids=counts.index, base=np.e)normal = metadata["tissue"] == "normal"tumor = metadata["tissue"] == "tumor"assert np.array_equal(metadata.loc[normal, "subject_id"], metadata.loc[tumor, "subject_id"])difference = shannon[tumor].to_numpy() - shannon[normal].to_numpy()interval = stats.t.interval(0.95, len(difference) - 1, loc=difference.mean(), scale=stats.sem(difference))print(f"Mean observed richness: {richness.mean():.3f}")print(f"Mean paired Shannon difference: {difference.mean():.6f}")print(f"95 percent interval: {interval[0]:.6f} to {interval[1]:.6f}")figure, axis = plt.subplots(figsize=(6, 4))for tissue in ["normal", "tumor"]: selected = metadata["tissue"] == tissue axis.scatter(counts.sum(axis=1)[selected], shannon[selected], alpha=0.65, label=tissue)axis.set(xscale="log", xlabel="Reads per sample", ylabel="Shannon diversity, natural log")axis.legend(title="Tissue")figure.tight_layout()figure.savefig(output / "alpha_diversity_python.png", dpi=160)plt.close(figure)metrics = {"first_shannon": float(shannon.iloc[0]), "mean_difference": float(difference.mean()), "lower": float(interval[0]), "upper": float(interval[1])}(output / "metrics_python.json").write_text(json.dumps(metrics))Mean observed richness: 197.849Mean paired Shannon difference: -0.45497695 percent interval: -0.639768 to -0.270183
Match the diversity question to the sampling effort
Section titled “Match the diversity question to the sampling effort”Observed richness generally increases as more reads reveal rare features. A raw richness comparison can therefore compare sequencing effort as well as communities. Shannon diversity is also affected by incomplete sampling.
Rarefaction asks what a sample would look like at a specified sampling effort. It discards observations in a single subsample and introduces sampling variation. Coverage based methods instead compare estimates at a stated completeness. Choose the target before choosing the method, and state how uncertainty enters the comparison. Chao and colleagues describe a unified approach to diversity rarefaction and extrapolation.
A diversity threshold must not become an automatic reason to exclude a sample. Low diversity can be the biology under study. Use the controls and assay evidence from QC and contamination to investigate it.
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”-
The manual defines Shannon diversity, its logarithm base, and observed richness. Its pooled diversity example differs from the mean of sample diversities used here.
-
Gloor and colleagues, Microbiome Datasets Are Compositional
The paper explains why sequencing depth and absolute microbial abundance are different quantities. That distinction limits a biological interpretation of richness or Shannon values.