# Computing diversity indices in R with vegan
# https://tidyecology.com/posts/diversity-indices-in-r/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-09-29

## ---- community-matrix ----
library(vegan)
library(dplyr)
library(ggplot2)

paper <- "#f5f4ee"; ink <- "#16241d"; forest <- "#275139"
gold  <- "#cda23f"; abandoned <- "#b5534e"; faint <- "#5d6b61"; line <- "#dad9ca"

theme_te <- theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = line, linewidth = 0.3),
        plot.background = element_rect(fill = paper, colour = NA),
        panel.background = element_rect(fill = paper, colour = NA),
        axis.title = element_text(colour = ink),
        axis.text = element_text(colour = faint),
        plot.title = element_text(colour = ink, face = "bold"))

community <- data.frame(
  row.names = c("Plot_A", "Plot_B", "Plot_C", "Plot_D"),
  Festuca   = c(10,  0, 25,  4),
  Trifolium = c( 8, 12,  2,  5),
  Plantago  = c( 5,  3,  1,  6),
  Achillea  = c( 2,  9,  0,  5),
  Lotus     = c( 0, 15,  0,  4)
)

community

## ---- compute-indices ----
richness <- specnumber(community)                 # number of species present
shannon  <- diversity(community, index = "shannon")
simpson  <- diversity(community, index = "simpson")

richness
shannon
simpson

## ---- shannon-reading ----
shannon_bits      <- diversity(community, index = "shannon", base = 2)
shannon_ceiling   <- log(richness)       # H' if every species were equally common
pielou_j          <- shannon / shannon_ceiling
effective_species <- exp(shannon)        # Hill number of order q = 1
plot_totals       <- rowSums(community)  # individuals counted per plot

shannon_reading <- data.frame(
  n       = plot_totals,
  S       = richness,
  H_nats  = round(shannon, 2),
  H_bits  = round(shannon_bits, 2),
  ln_S    = round(shannon_ceiling, 2),
  J       = round(pielou_j, 2),
  exp_H   = round(effective_species, 2)
)
shannon_reading

example_h <- c(2.1, 2.4)                 # two published-looking values

## ---- results-table ----
diversity_summary <- tibble(
  plot     = rownames(community),
  richness = richness,
  shannon  = round(shannon, 2),
  simpson  = round(simpson, 2)
) |>
  arrange(desc(shannon))

diversity_summary

## ---- fig-shannon ----
ggplot(diversity_summary, aes(x = reorder(plot, shannon), y = shannon)) +
  geom_col(fill = "#2f6b3e", width = 0.7) +
  geom_text(aes(label = shannon), hjust = -0.2, size = 3.5) +
  coord_flip() +
  labs(x = NULL, y = "Shannon diversity (H')") +
  ylim(0, max(diversity_summary$shannon) * 1.15) +
  theme_te
