# ggplot2 facets: fixed or free axis scales
# https://tidyecology.com/posts/fixed-or-free-scales-in-facets/
#
# 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-14

## ---- setup ----
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    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(),
          text             = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body),
          strip.text       = element_text(colour = te_ink, face = "bold"))
}

## ---- data ----
set.seed(1015)
sites <- data.frame(
  site   = c("Mill Pond", "Reed Bed", "Fen Edge", "Gravel Pit", "North Marsh", "Ditch Meadow"),
  start  = c(520, 180, 90, 40, 20, 6),                # expected count in 2013
  change = c(-0.10, 0.00, -0.40, 0.30, -0.70, -0.20)) # true change, 2013 to 2024
years <- 2013:2024

teal <- expand.grid(year = years, site = sites$site, stringsAsFactors = FALSE)
teal <- merge(teal, sites, by = "site")
teal <- teal[order(teal$site, teal$year), ]
teal$expected <- teal$start * (1 + teal$change)^((teal$year - 2013) / 11)
teal$count <- rpois(nrow(teal), teal$expected)
teal$site <- factor(teal$site, levels = sites$site)    # panel order = level order

head(teal[, c("site", "year", "count")], 3)

## ---- fit ----
fit <- glm(count ~ site * year, family = poisson, data = teal)
teal$fitted <- fitted(fit)

first <- teal[teal$year == 2013, ]
last  <- teal[teal$year == 2024, ]
fitted_change <- setNames(last$fitted / first$fitted - 1, as.character(first$site))
round(rbind(true = sites$change, fitted = fitted_change[sites$site]), 3)

## ---- three-plots ----
p_counts <- ggplot(teal, aes(year, count)) +
  geom_point(colour = te_forest, alpha = 0.6, size = 1.6) +
  geom_line(aes(y = fitted), colour = te_rust, linewidth = 0.9) +
  scale_x_continuous(breaks = c(2014, 2018, 2022)) +
  labs(x = NULL, y = "teal counted") +
  theme_datasheet()

p_fixed <- p_counts + facet_wrap(~ site)                     # the default: scales = "fixed"
p_free  <- p_counts + facet_wrap(~ site, scales = "free_y")  # each panel its own y range
p_both  <- p_counts + facet_wrap(~ site, scales = "free")    # x and y both free

## ---- scales-guard ----
panel_ranges <- function(p) {
  built <- ggplot_build(p)
  lay <- built$layout$layout                           # one row per panel
  ranges <- t(sapply(built$layout$panel_params, function(pp) pp$y.range))
  rownames(ranges) <- as.character(lay$site[order(as.integer(lay$PANEL))])
  ranges
}
pad <- function(r) r + c(-1, 1) * 0.05 * diff(r)       # the default expansion

stopifnot(identical(formals(facet_wrap)$scales, "fixed"))    # the default

# fixed: every panel gets the range of all the data
fixed_ranges <- panel_ranges(p_fixed)
all_data <- range(teal$count, teal$fitted)
stopifnot(all(apply(fixed_ranges, 1, function(r) isTRUE(all.equal(r, pad(all_data))))))

# free_y: each panel gets the range of its own points and line
free_ranges <- panel_ranges(p_free)
for (s in levels(teal$site)) {
  own <- range(teal$count[teal$site == s], teal$fitted[teal$site == s])
  stopifnot(isTRUE(all.equal(free_ranges[s, ], pad(own), check.attributes = FALSE)))
}

# free_y leaves x shared; panels follow the factor levels
built_free <- ggplot_build(p_free)
x_ranges <- sapply(built_free$layout$panel_params, function(pp) pp$x.range)
stopifnot(all(x_ranges == x_ranges[, 1]),
          identical(as.character(built_free$layout$layout$site), levels(teal$site)))

# free: with the same years at every site, it matches free_y here
both_x <- sapply(ggplot_build(p_both)$layout$panel_params, function(pp) pp$x.range)
stopifnot(isTRUE(all.equal(panel_ranges(p_both), free_ranges)), all(both_x == x_ranges))
round(cbind(fixed_ranges[, 2], free_ranges), 1)

## ---- line-move ----
line_move <- function(p, yvar) {
  ranges <- panel_ranges(p)
  heights <- ranges[, 2] - ranges[, 1]
  move <- setNames(last[[yvar]] - first[[yvar]], as.character(first$site))
  (move / heights[names(move)])[levels(teal$site)]
}

moves <- data.frame(true_change   = sites$change,
                    fitted_change = fitted_change[sites$site],
                    fixed         = line_move(p_fixed, "fitted"),
                    free_y        = line_move(p_free, "fitted"),
                    row.names     = sites$site)
round(moves, 3)

rank_fixed <- cor(moves$fixed,  moves$true_change, method = "spearman")
rank_free  <- cor(moves$free_y, moves$true_change, method = "spearman")
steep_free <- moves["North Marsh", "free_y"] / moves["Mill Pond", "free_y"]
steep_fit  <- moves["North Marsh", "fitted_change"] / moves["Mill Pond", "fitted_change"]
round(c(rank_fixed = rank_fixed, rank_free = rank_free, steep_free = steep_free), 2)

## ---- strip-labels ----
strip_label <- function(move) {
  setNames(sprintf("%s (true %+.0f%%)\nline %s %.0f%% of panel",
                   sites$site, 100 * sites$change,
                   ifelse(move < 0, "falls", "rises"), 100 * abs(move)),
           sites$site)
}

## ---- fig-free-y ----
p_free + facet_wrap(~ site, scales = "free_y",
                    labeller = as_labeller(strip_label(moves$free_y))) +
  theme(strip.text = element_text(size = 9, lineheight = 1.05))

## ---- replicates ----
one_survey <- function() {
  per_site <- t(sapply(seq_len(nrow(sites)), function(i) {
    mu <- sites$start[i] * (1 + sites$change[i])^((years - 2013) / 11)
    y  <- rpois(length(years), mu)
    f  <- fitted(glm(y ~ years, family = poisson))
    c(first = f[[1]], last = f[[length(f)]], low = min(y, f), high = max(y, f),
      ilow = min(y, f) / f[[1]], ihigh = max(y, f) / f[[1]])
  }))
  change <- per_site[, "last"] - per_site[, "first"]
  free   <- change / (1.1 * (per_site[, "high"] - per_site[, "low"]))
  fixed  <- change / (1.1 * (max(per_site[, "high"]) - min(per_site[, "low"])))
  index  <- (per_site[, "last"] / per_site[, "first"] - 1) /
            (1.1 * (max(per_site[, "ihigh"]) - min(per_site[, "ilow"])))
  c(fixed = cor(fixed, sites$change, method = "spearman"),
    free_y = cor(free, sites$change, method = "spearman"),
    index = cor(index, sites$change, method = "spearman"),
    steep_free = free[5] / free[1], f = free)          # f1 to f6: each panel's drawn move
}

set.seed(2015)
reps <- replicate(1000, one_survey())
rank_medians <- apply(reps[1:3, ], 1, median)
under_two <- mean(abs(reps["steep_free", ]) < 2)
under_two_mcse <- sqrt(under_two * (1 - under_two) / ncol(reps))
as_steep <- mean(abs(reps["steep_free", ]) >= steep_free)   # as kind as the data set above
free_reps <- reps[paste0("f", 1:6), ]
rownames(free_reps) <- sites$site
typical_move <- apply(free_reps, 1, median)
nm_less_steep <- mean(free_reps["North Marsh", ] > free_reps["Mill Pond", ])
round(c(rank_medians, steep_free_median = median(reps["steep_free", ]),
        share_under_2 = under_two, mc_se = under_two_mcse, as_steep = as_steep,
        nm_less_steep = nm_less_steep), 3)
round(typical_move, 2)

## ---- noise ----
change_birds <- sites$start * sites$change   # true change in birds, 2013 to 2024
noise_sd     <- sqrt(sites$start)            # Poisson SD at the 2013 count
names(change_birds) <- names(noise_sd) <- sites$site
in_noise_units <- change_birds / noise_sd
round(rbind(change_birds, noise_sd, in_noise_units), 2)

# which ranking does the drawn move under free_y follow, over the thousand surveys?
rank_noise <- median(apply(free_reps, 2, cor, y = in_noise_units, method = "spearman"))
rank_true  <- median(apply(free_reps, 2, cor, y = sites$change, method = "spearman"))
round(c(rank_noise = rank_noise, rank_true = rank_true), 2)

# the ceiling: a line can never cross more than 1/1.1 of its own free panel
stopifnot(all(abs(moves$free_y) <= 1 / 1.1),
          all(abs(free_reps) <= 1 / 1.1 + 1e-12))

## ---- index ----
teal$first_fit <- ave(teal$fitted, teal$site, FUN = function(v) v[1])
teal$index     <- teal$count / teal$first_fit
teal$index_fit <- teal$fitted / teal$first_fit
first <- teal[teal$year == 2013, ]
last  <- teal[teal$year == 2024, ]

p_index <- ggplot(teal, aes(year, index)) +
  geom_hline(yintercept = 1, colour = te_line, linewidth = 0.8) +
  geom_point(colour = te_forest, alpha = 0.6, size = 1.6) +
  geom_line(aes(y = index_fit), colour = te_rust, linewidth = 0.9) +
  scale_x_continuous(breaks = c(2014, 2018, 2022)) +
  facet_wrap(~ site) +
  labs(x = NULL, y = "count / fitted 2013 count") +
  theme_datasheet()

moves$index <- line_move(p_index, "index_fit")
index_height <- diff(panel_ranges(p_index)[1, ])
stopifnot(isTRUE(all.equal(moves$index * index_height, moves$fitted_change)))
rank_index <- cor(moves$index, moves$true_change, method = "spearman")
index_top <- names(which.max(tapply(teal$index, teal$site, max)))   # who sets the top
stopifnot(index_top == sites$site[which.min(sites$start)])          # the smallest site
round(moves[, c("true_change", "fitted_change", "index")], 3)

## ---- fig-index ----
p_index + facet_wrap(~ site, labeller = as_labeller(strip_label(moves$index))) +
  theme(strip.text = element_text(size = 9, lineheight = 1.05))

## ---- log-axis ----
p_log <- p_fixed + scale_y_log10()
log_height <- diff(panel_ranges(p_log)[1, ])           # in log10 units
log_change <- setNames(log10(last$fitted) - log10(first$fitted), as.character(first$site))
moves$log10 <- log_change[levels(teal$site)] / log_height
rank_log <- cor(moves$log10, moves$true_change, method = "spearman")

# a zero count on a log axis
zero_plot <- ggplot(data.frame(year = 1:3, count = c(3, 0, 2)), aes(year, count)) +
  geom_point() + scale_y_log10()
zero_warn <- character(0)
zero_built <- withCallingHandlers(ggplot_build(zero_plot), warning = function(w) {
  zero_warn <<- c(zero_warn, conditionMessage(w)); invokeRestart("muffleWarning") })
zero_grob <- suppressWarnings(ggplotGrob(zero_plot))
zero_panel <- zero_grob$grobs[[which(zero_grob$layout$name == "panel")]]
zero_points <- zero_panel$children[[grep("point", names(zero_panel$children))]]
stopifnot(is.infinite(log10(0)), any(grepl("introduced infinite values", zero_warn)),
          is.infinite(zero_built$data[[1]]$y[2]),                  # the zero became -Inf
          isTRUE(all.equal(as.numeric(zero_points$y)[2], 0)))      # drawn on the bottom edge
c(rank_log = round(rank_log, 2), zero_count_in_data = sum(teal$count == 0))
