# R0 and herd immunity
# https://tidyecology.com/posts/r0-and-herd-immunity/
#
# 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-07

## ---- setup ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_a <- "#3a6b52"; col_b <- "#b5651d"; col_ref <- "#555555"

R0 <- 4
herd <- 1 - 1/R0
Reff <- function(v, R0) R0*(1 - v)     # effective reproduction number after immunising fraction v
v_crit <- function(R0) 1 - 1/R0

## ---- reff ----
R0 <- 4
Reff <- function(v) R0*(1 - v)      # v = fraction immunised (or already immune)
c(none = Reff(0), quarter = Reff(0.25), half = Reff(0.5), three_quarters = Reff(0.75))

## ---- threshold ----
v_crit <- function(R0) 1 - 1/R0      # herd immunity threshold
c(R0_2 = v_crit(2), R0_4 = v_crit(4), R0_10 = v_crit(10))

## ---- fig-threshold ----
R0g <- seq(1, 12, 0.1)
dg <- data.frame(R0 = R0g, v = v_crit(R0g))
ggplot(dg, aes(R0, v)) +
  geom_line(colour = col_a, linewidth = 1) +
  geom_point(data = data.frame(R0 = 4, v = herd), aes(R0, v), colour = col_b, size = 2.6) +
  labs(x = "Basic reproduction number", y = "Fraction that must be immune",
       title = "More transmissible pathogens need more immunity")

## ---- fig-reff ----
vg <- seq(0, 1, 0.01)
dr <- do.call(rbind, lapply(c(2, 4, 10), function(r)
  data.frame(v = vg, Reff = r*(1 - vg), R0 = paste0("R0 = ", r))))
ggplot(dr, aes(v, Reff, colour = R0)) +
  geom_hline(yintercept = 1, colour = col_ref, linetype = "dotted") +
  geom_line(linewidth = 1) +
  coord_cartesian(ylim = c(0, 10)) +
  scale_colour_manual(values = c("R0 = 2" = col_a, "R0 = 4" = col_b, "R0 = 10" = col_ref)) +
  labs(x = "Fraction immunised", y = "Effective reproduction number", colour = NULL,
       title = "Immunity below the threshold slows the epidemic but does not stop it")
