# When not to use the Shannon diversity index
# https://tidyecology.com/posts/when-not-to-use-shannon/
#
# 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-10-15

## ---- setup ----
library(vegan)
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"))

## ---- two-communities ----
A <- c(50, 25, 12, 6, 3, 2, 1, 1)   # 8 species, uneven
B <- c(22, 20, 19, 18, 16)          # 5 species, even

H <- function(x) { p <- x / sum(x); -sum(p * log(p)) }

c(shannon_A = H(A), shannon_B = H(B),
  richness_A = sum(A > 0), richness_B = sum(B > 0),
  evenness_A = H(A) / log(sum(A > 0)),
  evenness_B = H(B) / log(sum(B > 0)))

## ---- fig-profile ----
qfull <- seq(0, 3, by = 0.05)
prof <- rbind(
  data.frame(q = qfull, D = as.numeric(renyi(A, scales = qfull, hill = TRUE)),
             community = "A: rich, uneven"),
  data.frame(q = qfull, D = as.numeric(renyi(B, scales = qfull, hill = TRUE)),
             community = "B: poor, even")
)

ggplot(prof, aes(q, D, colour = community)) +
  geom_line(linewidth = 1) +
  geom_vline(xintercept = 0.6, colour = faint, linetype = "dashed", linewidth = 0.4) +
  scale_colour_manual(values = c("A: rich, uneven" = abandoned,
                                 "B: poor, even" = forest)) +
  labs(x = "order q (weight on common species)",
       y = "effective number of species",
       colour = NULL, title = "Which community is more diverse? It depends on q") +
  theme_te + theme(legend.position = "top")

## ---- fig-samplesize ----
set.seed(88)
pool <- rep(seq_along(A), A * 40)        # large community with A's proportions
subsizes <- c(20, 50, 100, 300, 800)
res <- data.frame(
  n = subsizes,
  H = sapply(subsizes, function(n) {
    mean(replicate(200, { s <- sample(pool, n); p <- table(s) / n; -sum(p * log(p)) }))
  })
)

ggplot(res, aes(n, H)) +
  geom_hline(yintercept = H(A), colour = faint, linetype = "dashed") +
  geom_line(colour = gold, linewidth = 1) + geom_point(colour = gold, size = 2) +
  scale_x_log10(breaks = subsizes) +
  labs(x = "subsample size (log scale)", y = "estimated Shannon index",
       title = "Shannon drifts upward with sampling effort") +
  theme_te
