# Checking a phenology analysis
# https://tidyecology.com/posts/checking-a-phenology-analysis/
#
# 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(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())

## ---- thin ----
set.seed(505)
mu <- 128; sdev <- 12
full <- round(rnorm(300, mu, sdev))              # a well-monitored season
metrics <- function(x) c(first = min(x), mean = round(mean(x), 1), median = median(x))
m_full <- metrics(full)
m_50   <- metrics(sample(full, 150))             # keep half the records
m_20   <- metrics(sample(full, 60))              # keep a fifth
rbind(full = m_full, half = m_50, fifth = m_20)

## ---- thin-store ----
d_first_50 <- m_50["first"] - m_full["first"]
d_mean_50  <- m_50["mean"]  - m_full["mean"]
d_first_20 <- m_20["first"] - m_full["first"]

## ---- fig-thin ----
tdf <- data.frame(
  frac = rep(c(100, 50, 20), 3),
  day  = c(m_full["first"], m_50["first"], m_20["first"],
           m_full["mean"],  m_50["mean"],  m_20["mean"],
           m_full["median"],m_50["median"],m_20["median"]),
  metric = rep(c("first date", "mean date", "median date"), each = 3))
ggplot(tdf, aes(frac, day, colour = metric)) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.4) +
  scale_x_reverse(breaks = c(100, 50, 20)) +
  scale_colour_manual(values = c("first date" = terra, "mean date" = forest,
                                 "median date" = gold)) +
  labs(x = "per cent of records retained", y = "day of year", colour = NULL)

## ---- censor ----
set.seed(606)
win_lo <- 100; win_hi <- 165                     # the survey runs day 100 to 165
cold  <- round(rnorm(200, 116, 12))              # an early (cold-adapted) year
true_first <- min(cold)
seen  <- cold[cold >= win_lo & cold <= win_hi]   # only what falls inside the window
obs_first <- min(seen)
below <- mean(cold < win_lo)                      # fraction that flowered before the window
c(true_first = true_first, observed_first = obs_first,
  frac_before_window = round(below, 3))

## ---- censor-store ----
pct_before <- round(100 * below)
pinned <- obs_first == win_lo

## ---- fig-censor ----
cdf <- data.frame(day = cold, visible = cold >= win_lo)
ggplot(cdf, aes(day, fill = visible)) +
  annotate("rect", xmin = win_lo, xmax = win_hi, ymin = 0, ymax = Inf,
           fill = "#eef1e9") +
  geom_histogram(binwidth = 2, colour = "white") +
  geom_vline(xintercept = win_lo, colour = forest, linewidth = 0.8) +
  annotate("text", x = win_lo, y = 20, label = "survey opens", angle = 90,
           vjust = -0.3, hjust = 1, size = 3.3, colour = forest) +
  scale_fill_manual(values = c("FALSE" = terra, "TRUE" = "#b9c6b0"),
                    labels = c("FALSE" = "flowered unseen", "TRUE" = "recorded")) +
  labs(x = "day of year", y = "plants flowering", fill = NULL) +
  coord_cartesian(clip = "off") + theme(plot.margin = margin(12, 12, 6, 6))

## ---- agree ----
set.seed(707)
Y <- 15; sdev <- 12
temp <- rnorm(Y, 0, 1)
mean_true <- 130 - 3 * temp                       # true 3 days per degree
n_year <- round(exp(3.2 + 0.8 * temp))            # warm years better monitored
first <- mn <- med <- numeric(Y)
for (y in 1:Y) {
  x <- round(rnorm(n_year[y], mean_true[y], sdev))
  first[y] <- min(x); mn[y] <- mean(x); med[y] <- median(x)
}
slope <- function(z) coef(lm(z ~ temp))[2]
c(first = round(slope(first), 2), mean = round(slope(mn), 2),
  median = round(slope(med), 2))

## ---- agree-store ----
sl_first <- round(slope(first), 2)
sl_mean  <- round(slope(mn), 2)
sl_med   <- round(slope(med), 2)
