# Segmented regression for a breakpoint
# https://tidyecology.com/posts/segmented-regression-breakpoints/
#
# 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-05-31

## ---- setup ----
library(ggplot2)
te_ink <- "#16241d"; te_body <- "#2c3a31"; te_forest <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line <- "#dad9ca"; te_faint <- "#5d6b61"; te_gold <- "#cda23f"
te_green <- "#2f8f63"; te_terra <- "#b5534e"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(plot.background = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          axis.text = element_text(colour = te_faint, size = base_size - 2),
          axis.title = element_text(colour = te_body, size = base_size - 1),
          plot.title = element_text(colour = te_ink, face = "bold", size = base_size + 1),
          plot.subtitle = element_text(colour = te_label, size = base_size - 1),
          plot.caption = element_text(colour = te_faint, size = base_size - 3),
          legend.position = "top", plot.margin = margin(10, 12, 8, 10))
}

## ---- data ----
set.seed(4198)
n <- 120
nitrogen <- runif(n, 0, 30)             # kg N/ha/yr
psi_true <- 12                          # the real breakpoint
richness <- 25 + 0.10 * nitrogen - 0.90 * pmax(nitrogen - psi_true, 0) +
  rnorm(n, 0, 2.5)
dat <- data.frame(nitrogen, richness)

## ---- naive ----
fit_lin <- lm(richness ~ nitrogen, data = dat)
lin_slope <- coef(fit_lin)[["nitrogen"]]
lin_r2 <- summary(fit_lin)$r.squared

## ---- segmented ----
rss_at <- function(p) {
  hinge <- pmax(dat$nitrogen - p, 0)
  sum(lm(richness ~ nitrogen + hinge, data = dat)$residuals^2)
}
grid <- seq(3, 27, by = 0.1)
rss_grid <- vapply(grid, rss_at, numeric(1))
psi_hat <- optimize(rss_at, lower = grid[which.min(rss_grid)] - 0.2,
                    upper = grid[which.min(rss_grid)] + 0.2)$minimum

hinge <- pmax(dat$nitrogen - psi_hat, 0)
fit_seg <- lm(richness ~ nitrogen + hinge, data = dat)
cf <- coef(fit_seg)
below_slope <- cf[["nitrogen"]]
above_slope <- cf[["nitrogen"]] + cf[["hinge"]]
seg_r2 <- summary(fit_seg)$r.squared

## ---- fig-profile ----
prof <- data.frame(grid, rss_grid)
ggplot(prof, aes(grid, rss_grid)) +
  geom_vline(xintercept = psi_true, colour = te_sage, linewidth = 0.7, linetype = "22") +
  geom_line(colour = te_forest, linewidth = 1.0) +
  geom_point(data = data.frame(x = psi_hat, y = min(rss_grid)), aes(x, y),
             colour = te_gold, size = 2.6) +
  annotate("text", x = psi_true - 0.5, y = max(rss_grid) * 0.98, hjust = 1,
           label = "true", colour = te_label, size = 3.4) +
  annotate("text", x = psi_hat + 0.6, y = min(rss_grid) + 40, hjust = 0,
           label = "minimum", colour = te_label, size = 3.4) +
  labs(x = "Candidate breakpoint (kg N/ha/yr)", y = "Residual sum of squares",
       title = "The breakpoint is where the fit is tightest",
       subtitle = "Profile the RSS over every candidate, then take the minimum") +
  theme_te()

## ---- bootstrap ----
est_psi <- function(x, y) {
  f <- function(p) sum(lm(y ~ x + pmax(x - p, 0))$residuals^2)
  g <- seq(3, 27, by = 0.25)
  p0 <- g[which.min(vapply(g, f, numeric(1)))]
  optimize(f, lower = p0 - 0.5, upper = p0 + 0.5)$minimum
}
set.seed(101)
boot_psi <- replicate(2000, {
  i <- sample.int(n, n, replace = TRUE)
  est_psi(dat$nitrogen[i], dat$richness[i])
})
psi_ci <- quantile(boot_psi, c(0.025, 0.975))
psi_se <- sd(boot_psi)

## ---- fig-fits ----
gx <- seq(0, 30, length.out = 400)
pred <- data.frame(gx,
  seg = cf[[1]] + cf[[2]] * gx + cf[[3]] * pmax(gx - psi_hat, 0),
  lin = coef(fit_lin)[[1]] + coef(fit_lin)[[2]] * gx)
ggplot(dat, aes(nitrogen, richness)) +
  annotate("rect", xmin = psi_ci[[1]], xmax = psi_ci[[2]], ymin = -Inf, ymax = Inf,
           fill = te_sage, alpha = 0.20) +
  geom_point(colour = te_forest, alpha = 0.55, size = 1.7) +
  geom_line(data = pred, aes(gx, lin), colour = te_terra, linewidth = 1.0, linetype = "22") +
  geom_line(data = pred, aes(gx, seg), colour = te_forest, linewidth = 1.1) +
  geom_vline(xintercept = psi_hat, colour = te_gold, linewidth = 0.7) +
  annotate("text", x = 30, y = 17.6, hjust = 1, label = "single line (naive)",
           colour = te_terra, size = 3.4) +
  labs(x = "Nitrogen deposition (kg N/ha/yr)", y = "Species richness",
       title = "A single line hides the threshold",
       subtitle = "Broken-stick fit (solid) vs one straight line (dashed)") +
  theme_te()
