# Choosing colours for ecological data
# https://tidyecology.com/posts/choosing-colours-for-ecological-data/
#
# 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)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"))
}

## ---- colour-maths ----
hex_to_srgb <- function(hex) t(col2rgb(hex)) / 255
srgb_to_hex <- function(m) rgb(m[, 1], m[, 2], m[, 3])

linearise   <- function(u) ifelse(u <= 0.04045, u / 12.92, ((u + 0.055) / 1.055)^2.4)
delinearise <- function(u) ifelse(u <= 0.0031308, 12.92 * u, 1.055 * u^(1 / 2.4) - 0.055)

lum <- function(hex) as.numeric(linearise(hex_to_srgb(hex)) %*% c(0.2126, 0.7152, 0.0722))

m_xyz <- rbind(c(0.4124564, 0.3575761, 0.1804375),
               c(0.2126729, 0.7151522, 0.0721750),
               c(0.0193339, 0.1191920, 0.9503041))
d65 <- c(0.95047, 1, 1.08883)

lab_of <- function(hex) {
  xyz <- linearise(hex_to_srgb(hex)) %*% t(m_xyz)
  ratio <- t(t(xyz) / d65)
  f <- ifelse(ratio > (6 / 29)^3, ratio^(1 / 3), ratio * (29 / 6)^2 / 3 + 4 / 29)
  cbind(L = 116 * f[, 2] - 16, a = 500 * (f[, 1] - f[, 2]), b = 200 * (f[, 2] - f[, 3]))
}

de76 <- function(h1, h2) sqrt(rowSums((lab_of(h1) - lab_of(h2))^2))
de_pairs <- function(hex) {
  lb <- lab_of(hex); n <- length(hex); out <- matrix(0, n, n)
  for (i in seq_len(n)) out[i, ] <- sqrt(rowSums(t(t(lb) - lb[i, ])^2))
  dimnames(out) <- list(hex, hex)
  out
}

m_lms <- rbind(c(17.8824,    43.5161,  4.11935),
               c( 3.45565,   27.1554,  3.86714),
               c( 0.0299566,  0.184309, 1.46709))

simulate_cvd <- function(hex, type = "deutan") {
  lms <- linearise(hex_to_srgb(hex)) %*% t(m_lms)
  s <- diag(3)
  if (type == "deutan") s[2, ] <- c(0.494207, 0, 1.24827)
  if (type == "protan") s[1, ] <- c(0, 2.02344, -2.52581)
  back <- (lms %*% t(s)) %*% t(solve(m_lms))
  back[back < 0] <- 0
  back[back > 1] <- 1
  srgb_to_hex(delinearise(back))
}

round(c(luminance_white = lum("#FFFFFF"), luminance_black = lum("#000000"),
        luminance_mid_grey = lum("#808080"), lstar_mid_grey = lab_of("#808080")[1]), 4)
round(c(blue_yellow_normal = de76("#0000FF", "#FFFF00"),
        blue_yellow_deuteranope = de76(simulate_cvd("#0000FF"), simulate_cvd("#FFFF00")),
        red_green_normal = de76("#FF0000", "#00FF00"),
        red_green_deuteranope = de76(simulate_cvd("#FF0000"), simulate_cvd("#00FF00"))), 2)

## ---- ramps ----
viridis_anchor <- c("#440154", "#46337E", "#365C8D", "#277F8E",
                    "#1FA187", "#4AC16D", "#9FDA3A", "#FDE725")
ramp_from <- function(anchor, n) {
  m <- hex_to_srgb(anchor); k <- nrow(m)
  at <- seq(1, k, length.out = n)
  srgb_to_hex(cbind(approx(seq_len(k), m[, 1], at)$y,
                    approx(seq_len(k), m[, 2], at)$y,
                    approx(seq_len(k), m[, 3], at)$y))
}

n_lev <- 32
pal_rainbow <- rainbow(n_lev)
pal_seq     <- ramp_from(viridis_anchor, n_lev)

turning_points <- function(y) sum(diff(sign(diff(y))) != 0)
inversions <- function(y) {
  n <- length(y)
  sum(sapply(seq_len(n - 1), function(i) sum(y[(i + 1):n] < y[i])))
}
step_de <- function(p) de76(p[-length(p)], p[-1])

y_rain <- lum(pal_rainbow); y_seq <- lum(pal_seq)
s_rain <- step_de(pal_rainbow); s_seq <- step_de(pal_seq)

c(levels = n_lev, pairs = n_lev * (n_lev - 1) / 2, steps = n_lev - 1)
round(rbind(
  rainbow = c(lightest = max(y_rain), darkest = min(y_rain),
              turning_points = turning_points(y_rain),
              steps_downhill = sum(diff(y_rain) < 0),
              largest_fall = -min(diff(y_rain)),
              largest_drawdown = max(cummax(y_rain) - y_rain),
              order_inversions = inversions(y_rain)),
  sequential = c(max(y_seq), min(y_seq), turning_points(y_seq), sum(diff(y_seq) < 0),
                 -min(diff(y_seq)), max(cummax(y_seq) - y_seq), inversions(y_seq))), 4)

round(rbind(
  rainbow = c(mean_step = mean(s_rain), sd_step = sd(s_rain),
              cv_step = sd(s_rain) / mean(s_rain), smallest_step = min(s_rain),
              largest_step = max(s_rain), largest_over_smallest = max(s_rain) / min(s_rain),
              steps_under_half_mean = sum(s_rain < 0.5 * mean(s_rain))),
  sequential = c(mean(s_seq), sd(s_seq), sd(s_seq) / mean(s_seq), min(s_seq), max(s_seq),
                 max(s_seq) / min(s_seq), sum(s_seq < 0.5 * mean(s_seq)))), 4)

round(c(step_cv_ratio = (sd(s_rain) / mean(s_rain)) / (sd(s_seq) / mean(s_seq))), 4)

lstar_shape <- function(p) {
  lstar <- lab_of(p)[, 1]
  straight <- seq(lstar[1], lstar[length(lstar)], length.out = length(lstar))
  c(darkest_lstar = min(lstar), lightest_lstar = max(lstar),
    departure_from_a_straight_line = max(abs(lstar - straight)))
}
round(rbind(rainbow = lstar_shape(pal_rainbow), sequential = lstar_shape(pal_seq)), 4)

round(c(rainbow_turning_points_deuteranope = turning_points(lum(simulate_cvd(pal_rainbow))),
        rainbow_inversions_deuteranope = inversions(lum(simulate_cvd(pal_rainbow))),
        sequential_turning_points_deuteranope = turning_points(lum(simulate_cvd(pal_seq))),
        sequential_inversions_deuteranope = inversions(lum(simulate_cvd(pal_seq)))), 4)

## ---- fig-lightness ----
prof <- data.frame(
  pos = rep(seq_len(n_lev), 2),
  luminance = c(y_rain, y_seq),
  swatch = c(pal_rainbow, pal_seq),
  palette = factor(rep(c("rainbow(32)", "sequential, 32 levels"), each = n_lev),
                   levels = c("rainbow(32)", "sequential, 32 levels")))

ggplot(prof, aes(pos, luminance)) +
  geom_line(colour = "#2c3a31", linewidth = 0.7) +
  geom_point(aes(fill = swatch), shape = 21, size = 3.4, stroke = 0.45,
             colour = te_pal$ink) +
  scale_fill_identity() +
  scale_y_continuous(limits = c(0, 1)) +
  facet_wrap(~palette) +
  labs(x = "position along the palette", y = "relative luminance",
       title = "Only one of these two palettes gets lighter as the value rises") +
  theme_te() +
  theme(strip.text = element_text(colour = te_pal$ink, face = "bold"))

## ---- field ----
set.seed(20260806)
grid_n <- 48
smoother <- function(n, bw) exp(-0.5 * (outer(seq_len(n), seq_len(n), "-") / bw)^2)
kern <- smoother(grid_n, 4.5)
noise <- kern %*% matrix(rnorm(grid_n * grid_n), grid_n, grid_n) %*% t(kern)
noise <- noise / sd(as.vector(noise))
axis_u <- seq(0, 1, length.out = grid_n)
change <- 2.3 * noise + outer(axis_u, axis_u, function(a, b) 1.6 * a - 0.9 * b) + 0.55

mid_range <- mean(range(change))
round(c(grid_side = grid_n, cells = grid_n^2, mean_change = mean(change), sd_change = sd(change),
        smallest = min(change), largest = max(change),
        median_change = median(change), range_midpoint = mid_range,
        percent_positive = 100 * mean(change > 0)), 4)

round(c(percent_painted_positive_if_centred_on_range_midpoint =
          100 * mean(change > mid_range),
        percent_of_map_changing_apparent_sign = 100 * mean((change > 0) !=
          (change > mid_range)),
        percent_of_gains_painted_as_losses = 100 * mean(change[change > 0] < mid_range),
        percent_of_losses_painted_as_gains = 100 * mean(change[change < 0] > mid_range),
        percent_of_map_flipped_if_centred_on_median =
          100 * mean((change > 0) != (change > median(change)))), 4)

round(c(position_of_zero_along_a_sequential_ramp_percent =
          100 * (0 - min(change)) / diff(range(change)),
        percent_of_the_loss_ramp_the_worst_loss_reaches =
          100 * abs(min(change)) / max(abs(range(change)))), 4)

## ---- fig-diverging ----
div_anchor <- c("#6f2b27", te_pal$clay, "#c6c1ac", te_pal$green, te_pal$forest)
div_ramp <- ramp_from(div_anchor, 257)
half <- max(abs(range(change)))
rescale_to_key <- function(v, centre, half_width) {
  u <- half * (v - centre) / half_width
  u[u < -half] <- -half
  u[u > half] <- half
  u
}

cells <- expand.grid(x = seq_len(grid_n), y = seq_len(grid_n))
cells$value <- as.vector(change)
panels <- c("Centred on zero", "Spread over the data range")
map_df <- rbind(
  data.frame(cells, shown = rescale_to_key(cells$value, 0, half),
             panel = panels[1]),
  data.frame(cells, shown = rescale_to_key(cells$value, mid_range,
                                           diff(range(change)) / 2),
             panel = panels[2]))
map_df$panel <- factor(map_df$panel, levels = panels)

zero_line <- do.call(rbind, lapply(seq_along(
  contourLines(seq_len(grid_n), seq_len(grid_n), change, levels = 0)), function(i) {
    cl <- contourLines(seq_len(grid_n), seq_len(grid_n), change, levels = 0)[[i]]
    data.frame(x = cl$x, y = cl$y, piece = i)
  }))
zero_line <- do.call(rbind, lapply(panels, function(p)
  data.frame(zero_line, panel = factor(p, levels = panels))))

ggplot(map_df, aes(x, y)) +
  geom_raster(aes(fill = shown)) +
  geom_path(data = zero_line, aes(group = piece), colour = te_pal$ink, linewidth = 0.7) +
  scale_fill_gradientn(colours = div_ramp, limits = c(-half, half),
                       breaks = c(-8, -4, 0, 4, 8),
                       name = "change in species\nrichness (species)") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  facet_wrap(~panel) +
  guides(fill = guide_colourbar(barheight = unit(56, "pt"), barwidth = unit(9, "pt"),
                                frame.colour = te_pal$ink, ticks.colour = te_pal$ink)) +
  labs(x = NULL, y = NULL,
       title = "The colour boundary and the true zero are not the same line",
       subtitle = paste("Green is a gain in species richness and red a loss, and the black line is where the change is zero.",
                        "The key is the left-hand scale; on the right the same colours have been stretched over the data range.",
                        sep = "\n")) +
  theme_te() +
  theme(axis.text = element_blank(), axis.ticks = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_rect(colour = "#8f8d80", fill = NA, linewidth = 0.5),
        plot.subtitle = element_text(colour = "#2c3a31", size = 9),
        legend.title = element_text(colour = "#2c3a31", size = 9),
        legend.text = element_text(colour = "#2c3a31", size = 8),
        strip.text = element_text(colour = te_pal$ink, face = "bold"))

## ---- qualitative ----
hcl_chroma <- 100
hcl_lightness <- 65
gg_default <- function(n) hcl(h = seq(15, 375, length.out = n + 1)[seq_len(n)],
                              c = hcl_chroma, l = hcl_lightness)
c(hcl_chroma = hcl_chroma, hcl_lightness = hcl_lightness)

habitat  <- c("#d73027", "#1a9850", "#fee08b", "#4575b4", "#8c510a")
okabe    <- c("#E69F00", "#56B4E9", "#009E73", "#0072B2", "#D55E00")
default5 <- gg_default(5)
print(rbind(habitat = habitat, okabe_ito = okabe, ggplot2_default = default5))

off_diag <- function(m) m[upper.tri(m)]
threshold <- 10
palette_report <- function(p) {
  d_normal <- off_diag(de_pairs(p))
  d_deutan <- off_diag(de_pairs(simulate_cvd(p)))
  c(pairs = length(d_normal), closest_normal = min(d_normal),
    closest_deuteranope = min(d_deutan),
    largest_loss = max(d_normal - d_deutan),
    pairs_below_threshold = sum(d_deutan < threshold))
}
c(threshold_used = threshold, just_noticeable_difference_reference = 2.3)
print(round(rbind(habitat = palette_report(habitat), okabe_ito = palette_report(okabe),
                  ggplot2_default = palette_report(default5)), 3))

name_pair <- function(p, m) {
  m[lower.tri(m, diag = TRUE)] <- NA
  ij <- which(m == max(m, na.rm = TRUE), arr.ind = TRUE)[1, ]
  cat(p[ij[1]], "and", p[ij[2]], "seen as",
      simulate_cvd(p)[ij[1]], "and", simulate_cvd(p)[ij[2]], "\n")
  round(c(normal = de_pairs(p)[ij[1], ij[2]],
          deuteranope = de_pairs(simulate_cvd(p))[ij[1], ij[2]]), 3)
}
cat("habitat pair losing the most separation:\n")
print(name_pair(habitat, de_pairs(habitat) - de_pairs(simulate_cvd(habitat))))
cat("habitat pair closest after simulation:\n")
print(name_pair(habitat, -de_pairs(simulate_cvd(habitat))))
cat("ggplot2 default pair closest after simulation:\n")
print(name_pair(default5, -de_pairs(simulate_cvd(default5))))

by_n <- t(sapply(4:8, function(n) {
  d_normal <- off_diag(de_pairs(gg_default(n)))
  d_deutan <- off_diag(de_pairs(simulate_cvd(gg_default(n))))
  c(groups = n, pairs = length(d_normal), closest_normal = min(d_normal),
    closest_deuteranope = min(d_deutan), pairs_below_threshold = sum(d_deutan < threshold))
}))
print(round(by_n, 3))
okabe8 <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442",
            "#0072B2", "#D55E00", "#CC79A7", "#000000")
print(round(rbind(okabe_ito_eight = palette_report(okabe8)), 3))

## ---- fig-deuteranope ----
pal_names <- c("habitat set", "Okabe-Ito", "ggplot2 default")
views <- c("as drawn", "simulated deuteranope")
sw <- do.call(rbind, lapply(seq_along(pal_names), function(k) {
  p <- list(habitat, okabe, default5)[[k]]
  rbind(data.frame(class = seq_len(5), palette = pal_names[k], fill = p, view = views[1]),
        data.frame(class = seq_len(5), palette = pal_names[k],
                   fill = simulate_cvd(p), view = views[2]))
}))
sw$palette <- factor(sw$palette, levels = rev(pal_names))
sw$view <- factor(sw$view, levels = views)
contrast_ratio <- function(a, b) {
  la <- lum(a); lb <- lum(b)
  (pmax(la, lb) + 0.05) / (pmin(la, lb) + 0.05)
}
sw$ink <- ifelse(contrast_ratio(sw$fill, "#000000") >= contrast_ratio(sw$fill, "#ffffff"),
                 "#000000", "#ffffff")

ggplot(sw, aes(class, palette)) +
  geom_tile(aes(fill = fill), colour = te_pal$paper, linewidth = 1.4) +
  geom_text(aes(label = class, colour = ink), size = 4, show.legend = FALSE) +
  scale_fill_identity() +
  scale_colour_identity() +
  scale_x_continuous(breaks = seq_len(5)) +
  facet_wrap(~view) +
  labs(x = "habitat class", y = NULL,
       title = "The ggplot2 default is the palette that fails this test") +
  theme_te() +
  theme(panel.grid.major = element_blank(),
        strip.text = element_text(colour = te_pal$ink, face = "bold"))

## ---- greyscale ----
to_grey <- function(hex) {
  g <- delinearise(lum(hex))
  rgb(g, g, g)
}
lightness_gaps <- function(p) {
  lstar <- lab_of(p)[, 1]
  off_diag(abs(outer(lstar, lstar, "-")))
}
grey_report <- function(p) {
  gaps <- lightness_gaps(p)
  y <- lum(p)
  c(luminance_range = diff(range(y)),
    contrast_ratio_lightest_to_darkest = (max(y) + 0.05) / (min(y) + 0.05),
    closest_pair_in_lstar = min(gaps), pairs_within_10_lstar = sum(gaps < 10),
    pairs = length(gaps))
}
print(round(rbind(habitat = grey_report(habitat), okabe_ito = grey_report(okabe),
                  ggplot2_default = grey_report(default5),
                  okabe_ito_eight = grey_report(okabe8),
                  sequential_five = grey_report(ramp_from(viridis_anchor, 5))), 4))
print(rbind(as_drawn = default5, in_grey = to_grey(default5)))

## ---- fig-greyscale ----
set.seed(20260806)
n_year <- 12
years <- seq_len(n_year) + 2013
slopes <- c(0.9, -0.55, 0.3, -0.15, 0.05)
starts <- c(14, 26, 8, 19, 22)
trend_df <- do.call(rbind, lapply(seq_len(5), function(i) {
  data.frame(year = years, species = i,
             count = starts[i] + slopes[i] * seq_len(n_year) + rnorm(n_year, 0, 0.7))
}))

view_lab <- c("as drawn", "printed in grey", "grey plus symbol")
sp_lab   <- paste("species", seq_len(5))
sp_shape <- c(16, 17, 0, 4, 3)
sp_line  <- c("solid", "22", "44", "1343", "12")
panel_df <- do.call(rbind, lapply(seq_along(view_lab), function(k) {
  d <- trend_df
  d$view <- view_lab[k]
  d$col <- if (k == 1) default5[d$species] else to_grey(default5)[d$species]
  d$lt <- if (k == 3) sp_line[d$species] else "solid"
  d$shape <- if (k == 3) sp_shape[d$species] else NA_integer_
  d
}))
panel_df$view <- factor(panel_df$view, levels = view_lab)
key_grey <- to_grey(default5)[1]
panel_df$sp <- factor(sp_lab[panel_df$species], levels = sp_lab)
in3 <- panel_df$view == view_lab[3]

ggplot(panel_df, aes(year, count, group = species)) +
  geom_line(data = panel_df[!in3, ], aes(colour = col), linewidth = 0.8) +
  geom_line(data = panel_df[in3, ], aes(colour = col, linetype = sp), linewidth = 0.8) +
  geom_point(data = panel_df[in3, ], aes(colour = col, shape = sp), size = 2.6) +
  scale_colour_identity() +
  scale_linetype_manual(name = NULL, values = setNames(sp_line, sp_lab)) +
  scale_shape_manual(name = NULL, values = setNames(sp_shape, sp_lab)) +
  scale_x_continuous(breaks = c(2014, 2018, 2022)) +
  facet_wrap(~view) +
  guides(linetype = guide_legend(nrow = 1, override.aes = list(colour = key_grey)),
         shape = guide_legend(nrow = 1)) +
  labs(x = NULL, y = "count per transect",
       title = "A palette built on hue alone does not survive the photocopier") +
  theme_te() +
  theme(legend.position = "bottom",
        legend.key.width = unit(30, "pt"),
        strip.text = element_text(colour = te_pal$ink, face = "bold"))
