12  Alpha diversity

12.1 Background

Alpha diversity, or within-sample diversity, is a central concept in microbiome research. In ecological literature, several distinct but related alpha diversity indices, often referring to richness and evenness - the number of taxonomic features and how they are distributed, respectively - are commonly used (Whittaker 1960; Willis 2019). The term diversity can be used to collectively refer to all these indices.

Vegetation of the Siskiyou Mountains, Oregon and California. Whittaker (1960). Ecol Monogr 30:279–338. doi:10.2307/1943563.
Rarefaction, alpha diversity, and statistics. Willis (2019). Front Microbiol 10:2407. doi:10.3389/fmicb.2019.02407.

12.1.1 Applications

Alpha diversity is predominantly used to quantify complexity in the microbiome. In the general adult population, lower alpha diversity and lower bacterial load have been associated with worse overall physical and mental health (Vandeputte et al. 2017; Valles-Colomer et al. 2019). However, this principle may not generalize to other populations, most notably in early life and in patient cohorts (Ma et al. 2019).

Quantitative microbiome profiling links gut community variation to microbial load. Vandeputte et al. (2017). Nature 551:507–511. doi:10.1038/nature24460.
The neuroactive potential of the human gut microbiota in quality of life and depression. Valles-Colomer et al. (2019). Nat Microbiol. doi:10.1038/s41564-018-0337-x.
Diversity-disease relationships and shared species analyses for human microbiome-associated diseases. Ma et al. (2019). ISME J 13:1911–1919. doi:10.1038/s41396-019-0395-y.

12.1.2 Approaches

The majority of alpha diversity metrics are closely related, though this is not evident from their names. Bastiaanssen et al. (2023) lay out this relationship across two factors (see table below): first, alpha diversity metrics can be defined as special cases of a unifying equation of diversity, where the Hill number determines the specific index captured. Lower Hill numbers favor richness, the number of distinct taxonomic features, whereas higher numbers favor evenness, how the taxonomic features are distributed over the sample (Hill 1973). Second, some alpha diversity metrics are weighted based on phylogeny, like Faith’s PD (1992). The table includes Shannon entropy (Shannon 1948), Simpson’s index (Simpson 1949), phylogenetic entropy (Allen et al. 2009) and Rao’s quadratic diversity (Rao 1982).

Bugs as features (part 1): Concepts and foundations for the compositional data analysis of the microbiome–gut–brain axis. Bastiaanssen et al. (2023). Nat Ment Health 1:930–938. doi:10.1038/s44220-023-00148-3.
Diversity and Evenness: A Unifying Notation and Its Consequences. Hill (1973). Ecology 54:427–432. doi:10.2307/1934352.
Conservation evaluation and phylogenetic diversity. Faith (1992). Biol Conserv 61:1–10. doi:10.1016/0006-3207(92)91201-3.
Measurement of diversity. Simpson (1949). Nature 163:688. doi:10.1038/163688a0.
A new phylogenetic diversity measure generalizing the Shannon index and its application to phyllostomid bats. Allen et al. (2009). The American Naturalist 174:236–243. doi:10.1086/600101.
Diversity and dissimilarity coefficients: A unified approach. Rao (1982). Theoretical Population Biology 21:24–43. doi:10.1016/0040-5809(82)90004-1.
Hill number 0
Hill number 1
Hill number 2
Dependent on presence and absence of taxonomic features, not abundance Dependent on how evenly taxonomic features are distributed in a sample The inverse of the probability of two randomly picked individuals belonging to the same taxonomic feature
Neutral Diversity

Weighs each taxon equally, no assumptions about phylogeny

Richness (observed) Shannon Entropy Simpson’s Index
Phylogenetic Diversity

Indices are scaled based on phylogenetic closeness with a phylogenetic tree

Faith’s Phylogenetic Diversity Phylogenetic Entropy Rao’s Quadratic Diversity
The equation for general diversity can be defined as follows: \({}^qD = (\sum_{i=1}^{R}p^q_i)^{\frac{1}{(1-q)}}\), with q = Hill number, R = number of features, p = relative feature abundance.

Cassol et al. (2025) offer practical guidelines for selecting alpha diversity indices. They classify alpha diversity into four main categories and recommend calculating at least one metric from each category, if possible, to sufficiently capture within-sample diversity. Since indices within the same category tend to be correlated, they suggest using the simplest available metric. Below are the default choices for each category:

Diversity of planktonic foraminifera in deep-sea sediments. Berger et al. (1970). Science 168:1345–1347. doi:10.1126/science.168.3937.1345.
A mathematical theory of communication. Shannon (1948). Bell Syst Tech J 27:379–423. doi:10.1002/j.1538-7305.1948.tb01338.x.
Note: Richness estimators and denoising

Several estimators have been developed to address the confounding effect of limited sampling size on observed richness, most notably ACE (Chao and Lee 1992) and Chao1 (Chao 1984). Notably, these approaches may yield misleading results for modern 16S data, which commonly features denoising and removal of singletons (Deng et al. 2024).

Nonparametric richness estimators Chao1 and ACE must not be used with amplicon sequence variant data. Deng et al. (2024). ISME J 18:wrae106. doi:10.1093/ismejo/wrae106.
Non-parametric estimation of the number of classes in a population. Chao (1984). Scand J Stat 11:265–270. https://www.jstor.org/stable/4615964.
Estimating the number of classes via sample coverage. Chao et al. (1992). J Am Stat Assoc 87:210–217. doi:10.1080/01621459.1992.10475194.

12.2 Examples

12.2.1 Calculate diversity

Alpha diversity can be estimated with the addAlpha() function, which includes built-in methods for calculating some indices, while others are computed via integration with the vegan package (Oksanen et al. 2020). The method calculates the given indices, and adds them to the colData slot of the SummarizedExperiment object with the given name.

vegan: Community ecology package. Oksanen et al. (2020). R package version 2.5-7. https://CRAN.R-project.org/package=vegan.
# First, let's load some example data.
library(mia)
data("GlobalPatterns", package = "mia")
tse <- GlobalPatterns

# The 'index' parameter allows computing multiple diversity indices
# simultaneously. Without specification, four standard indices are calculated:
# dbp_dominance, faith_diversity, observed_richness, and shannon_diversity.
tse <- addAlpha(
    tse,
    assay.type = "counts"
)

# Check some of the first values in colData
tse$observed_richness |> head()
##  [1] 6964 7679 5729 2667 2574 3214
tse$shannon_diversity |> head()
##  [1] 6.577 6.777 6.498 3.828 3.288 4.289

Certain indices have additional options. For example, observed richness has the detection parameter that controls the detection threshold (by default 0). Features above this threshold are considered detected. See the full list of options from help(addAlpha).

Note: Faith’s diversity requires a tree

Because tse is a TreeSummarizedExperiment object, its phylogenetic tree is used by default. However, the optional argument tree must be provided if tse does not contain a rowTree.

12.2.2 Visualize diversity

As alpha diversity metrics typically summarize high-dimensional samples into single values, many visualization approaches are available. Once calculated, these metrics can be analyzed directly from the colData, for example, by plotting them using plotBoxplot() from the miaViz package. Here, we use the observed_richness as a measure of richness. Let’s visualize the results against the sample type in Figure 12.1.

library(miaViz)
plotBoxplot(
    tse,
    col.var = "observed_richness",
    x = "SampleType"
) +
    theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
    labs(x = "Sample type", y = "Observed richness")
Box plots of observed richness on the y-axis for each sample type on the x-axis, with individual samples overlaid as points.
Figure 12.1: Observed richness of the GlobalPatterns samples grouped by sample type (x-axis).

12.2.2.1 Comparing alpha diversity indices

We can compare alpha diversities for example by calculating the correlation between them. Figure 12.2 shows a visual comparison between Shannon and Faith indices as a scatter plot.

library(scater)
plotColData(tse, x = "shannon_diversity", y = "faith_diversity") +
    labs(x = "Shannon index", y = "Faith (phylogenetic) index") +
    geom_smooth(method = "lm")
Scatter plot of samples with the Shannon index on the x-axis and Faith's phylogenetic diversity on the y-axis, with a linear regression line and a shaded confidence band.
Figure 12.2: Scatter plot of Shannon index (x-axis) against Faith’s phylogenetic diversity (y-axis) in the GlobalPatterns samples, with a fitted linear regression line and its confidence band.
cor.test(tse[["shannon_diversity"]], tse[["faith_diversity"]])
##  
##      Pearson's product-moment correlation
##  
##  data:  tse[["shannon_diversity"]] and tse[["faith_diversity"]]
##  t = 2.2, df = 24, p-value = 0.04
##  alternative hypothesis: true correlation is not equal to 0
##  95 percent confidence interval:
##   0.02719 0.68822
##  sample estimates:
##     cor 
##  0.4102

Let us visualize results from multiple alpha diversity measures against a given sample grouping available in colData (here, sample type). These have been readily stored in the colData slot, and they are thus directly available for plotting (Figure 12.3).

Show the plotting code
library(patchwork)

# Create the plots
p1 <- plotBoxplot(
    tse,
    col.var = "observed_richness", x = "SampleType", fill.by = "SampleType"
) +
    labs(y = "Observed richness", fill = "Sample type")
p2 <- plotBoxplot(
    tse,
    col.var = "dbp_dominance", x = "SampleType", fill.by = "SampleType"
) +
    labs(y = "Berger-Parker dominance", fill = "Sample type")
p3 <- plotBoxplot(
    tse,
    col.var = "shannon_diversity", x = "SampleType", fill.by = "SampleType"
) +
    labs(y = "Shannon diversity", fill = "Sample type")
p4 <- plotBoxplot(
    tse,
    col.var = "faith_diversity", x = "SampleType", fill.by = "SampleType"
) +
    labs(y = "Faith's PD", fill = "Sample type")

# Combine the plots and remove the sample type labels from the x-axis
wrap_plots(p1, p2, p3, p4, ncol = 1) +
    plot_layout(guides = "collect") &
    theme(
        axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.ticks.x = element_blank()
    )
Four box plot panels stacked vertically for observed richness, Berger-Parker dominance, Shannon diversity and Faith's phylogenetic diversity, each with one box per sample type filled in a different colour. Soil and freshwater creek samples have the highest richness, and tongue samples have the lowest.
Figure 12.3: Observed richness, Berger-Parker dominance, Shannon diversity and Faith’s phylogenetic diversity (panels from top to bottom) of the GlobalPatterns samples, grouped and colored by sample type.

All these different metrics provide information from different aspects of alpha diversity, notably on richness, dominance, information, and phylogenetic diversity described in Cassol et al. (2025). It is recommended to interpret these aspects separately and together.

Key features and guidelines for the application of microbial alpha diversity metrics. Cassol et al. (2025). Sci Rep 15:622. doi:10.1038/s41598-024-77864-y.

From our example, we can observe that soil and freshwater (creek) have the highest number of different taxonomic features present while tongue microbiome has the lowest richness, suggesting greater biodiversity in soil and freshwater samples.

Based on the dominance values, species abundances in the soil samples appeared to be relatively evenly distributed. In contrast, the freshwater microbiome — particularly in the freshwater creek samples — was dominated by a single species, despite showing high observed richness.

These observations are supported by the Shannon index, which accounts for both richness and dominance. Soil samples showed the highest Shannon diversity, reflecting their high number of observed species and relatively even species distribution.

Soil and freshwater creek environments host a wide range of phylogenetically diverse organisms, indicating that the observed taxonomic features are not closely related but rather distinct from one another in terms of their evolutionary history.

In summary, soil samples exhibit the highest biodiversity, while human-derived samples show less variation in terms of species composition and evolutionary diversity.

12.2.3 Rarefaction

To control for uneven sampling depths, we can do rarefaction (Sanders 1968; Hurlbert 1971) (see Section 10.5). Rarefaction for alpha diversity metrics can be applied by specifying the optional arguments sample and niter in addAlpha(). niter controls the number of rarefaction iterations (choose a sufficiently large value for stable estimates). sample sets the rarefaction depth, i.e., the number of reads sampled per iteration from each sample (default: the smallest library size).

Marine benthic diversity: A comparative study. Sanders (1968). The American Naturalist 102:243–282. doi:10.1086/282541.
The nonconcept of species diversity: A critique and alternative parameters. Hurlbert (1971). Ecology 52:577–586. doi:10.2307/1934145.
set.seed(123)
tse <- addAlpha(
    tse,
    assay.type = "counts",
    index = "observed_richness",
    name = "richness_w_rarefaction",
    niter = 10
)

Next, we compare the results with and without rarefaction (Figure 12.4).

library(miaViz)

p1 <- plotBoxplot(tse, col.var = "observed_richness", fill.by = "SampleType") +
    labs(y = "Observed richness", fill = "Sample type")
p2 <- plotBoxplot(tse, col.var = "richness_w_rarefaction", fill.by = "SampleType") +
    labs(y = "Observed richness (rarefied)", fill = "Sample type")
p1 + p2 + plot_layout(guides = "collect")
Two box plot panels side by side for observed richness without and with rarefaction, with boxes filled by sample type. The rarefied values are lower and the ranking of sample types changes, while soil stays the richest.
Figure 12.4: Boxplots of observed richness in the GlobalPatterns samples without (left) and with (right) rarefaction, colored by sample type.

These results illustrate that uneven sequencing depth affects the diversity estimates. The rarefied values are lower, as every sample is subsampled to the same, smaller depth, and the ranking of the sample types changes. Skin and estuary sediment samples, which have relatively few reads, rank higher after rarefaction, whereas the deeply sequenced freshwater samples rank lower. Soil remains the richest sample type in both analyses. This indicates that part of the apparent differences in the non-rarefied analysis was driven by sampling effort rather than biology.

12.2.4 Statistical testing

We can then analyze the statistical significance. We use the non-parametric Wilcoxon or Mann-Whitney test (Wilcoxon 1945; Mann and Whitney 1947), as it is more flexible than the commonly used Student’s t-test, since it does not assume normality.

Individual comparisons by ranking methods. Wilcoxon (1945). Biometrics Bull 1:80. doi:10.2307/3001968.
On a test of whether one of two random variables is stochastically larger than the other. Mann et al. (1947). Ann Math Stat 18:50–60. doi:10.1214/aoms/1177730491.
pairwise.wilcox.test(
    tse[["observed_richness"]], tse[["SampleType"]],
    p.adjust.method = "fdr"
)
##  
##      Pairwise comparisons using Wilcoxon rank sum exact test 
##  
##  data:  tse[["observed_richness"]] and tse[["SampleType"]] 
##  
##                     Feces Freshwater Freshwater (creek) Mock Ocean
##  Freshwater         0.3   -          -                  -    -    
##  Freshwater (creek) 0.3   0.4        -                  -    -    
##  Mock               0.3   0.9        0.3                -    -    
##  Ocean              0.8   1.0        0.3                1.0  -    
##  Sediment (estuary) 0.3   0.9        0.3                0.6  0.6  
##  Skin               0.3   0.9        0.3                1.0  1.0  
##  Soil               0.3   0.4        0.9                0.3  0.3  
##  Tongue             1.0   0.6        0.4                0.6  0.6  
##                     Sediment (estuary) Skin Soil
##  Freshwater         -                  -    -   
##  Freshwater (creek) -                  -    -   
##  Mock               -                  -    -   
##  Ocean              -                  -    -   
##  Sediment (estuary) -                  -    -   
##  Skin               0.6                -    -   
##  Soil               0.3                0.3  -   
##  Tongue             0.4                0.6  0.4 
##  
##  P value adjustment method: fdr

With only two to four samples per sample type, none of the pairwise differences is significant after FDR correction.

12.2.4.1 Visualizing significance in group-wise comparisons

Next, let’s compare the Shannon index between sample groups and visualize the statistical significance. plotBoxplot() can annotate pairwise group comparisons directly. By default, it uses Wilcoxon tests and adjusts p-values with the FDR method (Benjamini and Hochberg 1995). The resulting plot is shown in Figure 12.5.

Controlling the false discovery rate: A practical and powerful approach to multiple testing. Benjamini et al. (1995). J R Stat Soc Series B 57:289–300. doi:10.1111/J.2517-6161.1995.TB02031.X.
# Subsets the data by selecting only samples from feces, skin, or tongue.
tse_sub <- tse[, tse[["SampleType"]] %in% c("Feces", "Skin", "Tongue")]

plotBoxplot(
    tse_sub,
    col.var = "shannon_diversity",
    x = "SampleType",
    add.significance = TRUE,
    label = "p.adj"
) +
    labs(x = "Sample type", y = "Shannon diversity")
Three box plots of Shannon diversity, one each for feces, skin and tongue samples, with brackets above the boxes connecting each pair of groups and labeled with adjusted p-values.
Figure 12.5: Shannon diversity in feces, skin and tongue samples of the GlobalPatterns data shown as boxplots, annotated with FDR-adjusted p-values from pairwise Wilcoxon tests.

12.3 Further reading

An article on ggpubr package provides further examples for estimating and highlighting significances.

12.4 Exercises

We use the Tengeler2020 dataset.

Solve the exercises in order, as each exercise continues from the previous one. Try to solve each exercise yourself before opening the solution.

Exercise 1: Richness and evenness

Goal: Explain what richness and evenness mean.

Imagine two samples that both contain the same four taxa and 100 reads in total:

Taxon Sample A Sample B
Taxon 1 25 97
Taxon 2 25 1
Taxon 3 25 1
Taxon 4 25 1

Answer the following questions without writing any code. The Background section at the beginning of this chapter will help you.

  1. What is the observed richness of each sample?

  2. Which sample is more even?

  3. Which sample would you expect to have a higher Shannon diversity? Why?

  4. Which sample would you expect to have a higher Berger-Parker dominance?

  1. The observed richness is the number of taxa present. Both samples contain four taxa, so both have an observed richness of 4.

  2. Sample A is more even, because all taxa have the same abundance. In Sample B, one taxon has almost all the reads.

  3. Sample A. Shannon diversity accounts for both richness and evenness. The samples have the same richness, but Sample A is more even.

  4. Sample B. Berger-Parker dominance is the relative abundance of the most abundant taxon: 0.97 in Sample B and 0.25 in Sample A.

Richness alone cannot tell these two samples apart. This is why it is recommended to calculate several indices that describe different aspects of alpha diversity.

Exercise 2: Calculate alpha diversity

Goal: Calculate alpha diversity indices and find where they are stored.

  1. Load the Tengeler2020 dataset from the mia package and store it in a variable called tse.

  2. Calculate alpha diversity with addAlpha() from the counts assay. Use the default indices, that is, do not specify the index argument.

  3. Check the column names of colData(tse). Which new columns were added?

  4. Each of the default indices represents one of the four categories of alpha diversity described in the Background section of this chapter. Match each new column to its category: richness, dominance, information or phylogenetics.

  5. Show the first values of the Shannon diversity.

Useful functions: data(), mia::addAlpha(), colData(), colnames(), head()

library(mia)

# 1. Load the data
data("Tengeler2020", package = "mia")
tse <- Tengeler2020

# 2. Calculate the default alpha diversity indices
tse <- addAlpha(tse, assay.type = "counts")

# 3. Check the columns of colData
colnames(colData(tse))
##  [1] "patient_status"           "cohort"                  
##  [3] "patient_status_vs_cohort" "sample_name"             
##  [5] "dbp_dominance"            "faith_diversity"         
##  [7] "observed_richness"        "shannon_diversity"

# 5. Show the first values of Shannon diversity
head(tse$shannon_diversity)
##  [1] 1.765 2.716 3.178 2.892 2.842 2.798
  1. The new columns and their categories are:
  • observed_richness: richness
  • dbp_dominance: dominance (Berger-Parker)
  • shannon_diversity: information
  • faith_diversity: phylogenetics. It can be calculated because the dataset contains a phylogenetic tree in rowTree(tse).
Exercise 3: Compare alpha diversity indices

Goal: Compare alpha diversity indices with each other.

  1. Make a scatter plot with the observed richness on the x-axis and the Shannon diversity on the y-axis. Add a linear regression line to the plot.

  2. Calculate the correlation between the observed richness and the Shannon diversity, and test whether it is statistically significant.

  3. Look at the plot and the correlation. Do the two indices give similar information? Think about what each index measures (see Exercise 1).

Useful functions: scater::plotColData(), ggplot2::geom_smooth(), stats::cor.test()

library(scater)

# 1. Scatter plot with a linear regression line
plotColData(tse, x = "observed_richness", y = "shannon_diversity") +
    geom_smooth(method = "lm") +
    labs(x = "Observed richness", y = "Shannon diversity")


# 2. Correlation and its significance
cor.test(tse$observed_richness, tse$shannon_diversity)
##  
##      Pearson's product-moment correlation
##  
##  data:  tse$observed_richness and tse$shannon_diversity
##  t = 3.4, df = 25, p-value = 0.002
##  alternative hypothesis: true correlation is not equal to 0
##  95 percent confidence interval:
##   0.2318 0.7764
##  sample estimates:
##     cor 
##  0.5623
  1. Observed richness only counts the taxa, while Shannon diversity also accounts for how evenly the reads are distributed among them. A strong correlation means that the indices largely carry the same information in this dataset. A weak correlation means that evenness differs between samples independently of richness, and the indices describe different aspects of the communities.
Exercise 4: Rarefaction

Goal: Account for uneven sequencing depth with rarefaction.

  1. Calculate the library size of each sample, that is, the total number of reads in each sample. Summarize the library sizes. How large is the difference between the smallest and the largest library?

  2. Calculate the observed richness again with rarefaction. Set the rarefaction depth sample to the smallest library size, use niter = 10 iterations, and store the result in colData under the name "richness_rarefied". Set a seed before the calculation, as rarefaction is random.

  3. Visualize the observed richness without rarefaction as boxplots, with one box for each group in patient_status. Then make the same plot for the observed richness with rarefaction, and compare the two plots.

  4. Why might the two values differ? Why do we use the smallest library size as the rarefaction depth?

Useful functions: assay(), colSums(), summary(), min(), set.seed(), mia::addAlpha(), miaViz::plotBoxplot()

# 1. Library sizes
lib_size <- colSums(assay(tse, "counts"))
summary(lib_size)
##     Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     1772   11804   16745   17997   21502   40584

# 2. Observed richness with rarefaction
set.seed(123)
tse <- addAlpha(
    tse,
    assay.type = "counts",
    index = "observed_richness",
    name = "richness_rarefied",
    sample = min(lib_size),
    niter = 10
)

# 3. Compare richness without and with rarefaction
library(miaViz)

plotBoxplot(tse, col.var = "observed_richness", x = "patient_status") +
    labs(x = "Patient status", y = "Observed richness")

plotBoxplot(tse, col.var = "richness_rarefied", x = "patient_status") +
    labs(x = "Patient status", y = "Observed richness (rarefied)")

  1. The more reads a sample has, the more taxa are likely to be detected. Without rarefaction, part of the differences in richness can therefore be due to differences in sequencing depth. Rarefaction subsamples every sample to the same number of reads, so the samples are compared at equal depth. The depth cannot be larger than the smallest library, because a sample cannot be subsampled to more reads than it contains. Samples with fewer reads than the chosen depth would have to be removed.
Exercise 5: Compare groups

Goal: Compare alpha diversity between sample groups and test the difference statistically.

  1. Visualize the Shannon diversity of the samples as boxplots, with one box for each group in patient_status.

  2. Test whether the Shannon diversity differs between the groups with the Wilcoxon test.

  3. Add the p-value of the test to the boxplot.

  4. Why does this chapter use the Wilcoxon test instead of Student’s t-test?

Useful functions: miaViz::plotBoxplot(), stats::wilcox.test()

# 1. Boxplot of Shannon diversity by group
plotBoxplot(tse, col.var = "shannon_diversity", x = "patient_status") +
    labs(x = "Patient status", y = "Shannon diversity")


# 2. Wilcoxon test
wilcox.test(shannon_diversity ~ patient_status, data = colData(tse))
##  
##      Wilcoxon rank sum exact test
##  
##  data:  shannon_diversity by patient_status
##  W = 61, p-value = 0.2
##  alternative hypothesis: true location shift is not equal to 0

# 3. Boxplot with the p-value
plotBoxplot(
    tse,
    col.var = "shannon_diversity",
    x = "patient_status",
    add.significance = TRUE
) +
    labs(x = "Patient status", y = "Shannon diversity")

  1. Student’s t-test assumes that the values are normally distributed in each group. The Wilcoxon test is non-parametric and does not make this assumption, so it is more flexible for alpha diversity values, which are often not normally distributed.
Back to top