# Phenological trends and temperature
# https://tidyecology.com/posts/phenological-trends-and-temperature/
#
# 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 ----
library(ggplot2)
forest <- "#275139"; gold <- "#cda23f"; terra <- "#b5534e"; mown <- "#2f8f63"
theme_te <- function(base = 13) {
  theme_minimal(base_size = base) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6da", linewidth = 0.3),
          axis.title = element_text(colour = "#46604a"),
          axis.text  = element_text(colour = "#2c3a31"),
          plot.title = element_text(colour = "#16241d", face = "bold"),
          plot.subtitle = element_text(colour = "#5d6b61"),
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          legend.position = "bottom", legend.title = element_text(colour = "#46604a"))
}
theme_set(theme_te())

## ---- data ----
set.seed(303)
Y <- 30
beta_true <- 3                                   # true days earlier per degree
sdev <- 12
temp <- rnorm(Y, 0, 1)                            # standardised spring temperature
mean_true <- 130 - beta_true * temp               # true mean date each year
n_year <- round(exp(3.0 + 0.9 * temp))            # warm years -> more plants observed

first_obs <- mean_obs <- numeric(Y)
for (y in 1:Y) {
  x <- draw <- round(rnorm(n_year[y], mean_true[y], sdev))
  first_obs[y] <- min(x); mean_obs[y] <- mean(x)
}
range(n_year)

## ---- eff-store ----
n_lo <- range(n_year)[1]; n_hi <- range(n_year)[2]

## ---- fits ----
fit_mean  <- lm(mean_obs  ~ temp)
fit_first <- lm(first_obs ~ temp)
s_mean  <- coef(fit_mean)[2];  ci_mean  <- confint(fit_mean)[2, ]
s_first <- coef(fit_first)[2]; ci_first <- confint(fit_first)[2, ]
rbind(mean_date  = c(slope = s_mean,  ci_mean),
      first_date = c(slope = s_first, ci_first))

## ---- fit-store ----
sm  <- sprintf("%.2f", s_mean);  cml <- sprintf("%.2f", ci_mean[1]);  cmh <- sprintf("%.2f", ci_mean[2])
sf  <- sprintf("%.2f", s_first); cfl <- sprintf("%.2f", ci_first[1]); cfh <- sprintf("%.2f", ci_first[2])
ratio_est  <- round(s_first / s_mean, 1)
ratio_true <- round(abs(s_first) / beta_true, 1)

## ---- fig-sensitivity ----
plotdf <- rbind(
  data.frame(temp = temp, day = mean_obs,  metric = "mean date"),
  data.frame(temp = temp, day = first_obs, metric = "first date"))
ggplot(plotdf, aes(temp, day, colour = metric)) +
  geom_point(size = 2.2, alpha = 0.8) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 0.9, formula = y ~ x) +
  scale_colour_manual(values = c("mean date" = forest, "first date" = terra)) +
  labs(x = "standardised spring temperature", y = "day of year", colour = NULL)

## ---- control ----
set.seed(404)
first_const <- numeric(Y)
for (y in 1:Y) first_const[y] <- min(round(rnorm(30, mean_true[y], sdev)))
s_const <- coef(lm(first_const ~ temp))[2]
round(s_const, 2)

## ---- control-store ----
sc <- round(s_const, 2)

## ---- fig-control ----
cdf <- rbind(
  data.frame(temp = temp, day = first_obs,   effort = "effort tracks warmth"),
  data.frame(temp = temp, day = first_const, effort = "effort held constant"))
ggplot(cdf, aes(temp, day, colour = effort, linetype = effort)) +
  geom_point(size = 2.2, alpha = 0.85) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 0.9, formula = y ~ x) +
  scale_colour_manual(values = c("effort tracks warmth" = terra,
                                 "effort held constant" = forest)) +
  scale_linetype_manual(values = c("effort tracks warmth" = 2,
                                    "effort held constant" = 1)) +
  labs(x = "standardised spring temperature", y = "first observed date", colour = NULL,
       linetype = NULL)
