# PLS 206 Friday: publication-ready figures in R
# Grey Monroe, Fall 2026


#### Step 0. Set up ####

# install.packages(c("ggplot2", "patchwork"))

library(ggplot2)
library(patchwork)

wheat <- read.csv("https://greymonroe.github.io/PLS_206/data/wheat_trial.csv")
str(wheat)

figure_dir <- "~/Desktop"   # change to wherever you want your figures to go


#### Step 1. The default ####

ggplot(wheat, aes(nitrogen, yield, colour = water)) +
  geom_point()


#### Step 2. Decide the size first ####

p <- ggplot(wheat, aes(nitrogen, yield, colour = water)) +
  geom_point()

ggsave(file.path(figure_dir, "step2.png"), p, width = 89, height = 60, units = "mm", dpi = 600)


#### Step 3. A clean theme, at the right text size ####

theme_pub <- theme_classic(base_size = 6, base_family = "Helvetica") +
  theme(axis.text = element_text(size = 5),
        axis.ticks.length = unit(2, "pt"),
        legend.title = element_text(size = 6, face = "bold"),
        legend.text = element_text(size = 5),
        legend.key.size = unit(0.3, "lines"),
        legend.background = element_blank(),
        strip.background = element_blank(),
        plot.tag = element_text(size = 8, face = "bold"),
        plot.margin = margin(2, 2, 2, 2),
        plot.background = element_rect(fill = "transparent", colour = NA),
        panel.background = element_rect(fill = "transparent", colour = NA))

p <- p + theme_pub
ggsave(file.path(figure_dir, "step3.png"), p, width = 89, height = 60, units = "mm", dpi = 600)


#### Step 4. Labels with units, and a legend that doesn't steal space ####

p <- ggplot(wheat, aes(nitrogen, yield, colour = water)) +
  geom_point(size = 0.9, alpha = 0.8) +
  scale_colour_manual(values = c(control = "#4E79A7", drought = "#F28E2B"),
                      name = "Water", labels = c("Control", "Drought")) +
  labs(x = expression("Nitrogen (kg ha"^-1*")"),
       y = expression("Grain yield (t ha"^-1*")")) +
  theme_pub +
  theme(legend.position = "inside",
        legend.position.inside = c(0.04, 0.94),
        legend.justification = c(0, 1))

ggsave(file.path(figure_dir, "step4.png"), p, width = 89, height = 60, units = "mm", dpi = 600)


#### Step 5. Colours everyone can read ####

okabe_ito <- c("#F28E2B", "#56B4E9", "#009E73", "#F0E442",
               "#4E79A7", "#D55E00", "#CC79A7", "#000000")


#### Step 6. Show the model, not just the points ####

fit <- lm(yield ~ nitrogen * water, data = wheat)

new <- expand.grid(nitrogen = seq(min(wheat$nitrogen), max(wheat$nitrogen), length.out = 100),
                   water = c("control", "drought"))
new <- cbind(new, predict(fit, newdata = new, interval = "confidence"))

water_cols <- c(control = "#4E79A7", drought = "#F28E2B")

p_a <- ggplot(wheat, aes(nitrogen, yield, colour = water)) +
  geom_ribbon(data = new, aes(y = fit, ymin = lwr, ymax = upr, fill = water),
              colour = NA, alpha = 0.2, show.legend = FALSE) +
  geom_point(size = 0.9, alpha = 0.8) +
  geom_line(data = new, aes(y = fit), linewidth = 0.4) +
  scale_colour_manual(values = water_cols, name = "Water", labels = c("Control", "Drought")) +
  scale_fill_manual(values = water_cols) +
  labs(x = expression("Nitrogen (kg ha"^-1*")"),
       y = expression("Grain yield (t ha"^-1*")")) +
  theme_pub +
  theme(legend.position = "inside",
        legend.position.inside = c(0.04, 0.94),
        legend.justification = c(0, 1))

ggsave(file.path(figure_dir, "step6.png"), p_a, width = 89, height = 60, units = "mm", dpi = 600)


#### Step 7. Groups: show the data, not a bar ####

fit_v <- lm(yield ~ variety * water, data = wheat)

means <- expand.grid(variety = c("Amber", "Bronze", "Copper"),
                     water = c("control", "drought"))
means <- cbind(means, predict(fit_v, newdata = means, interval = "confidence"))

p_b <- ggplot(wheat, aes(variety, yield, colour = water)) +
  geom_point(position = position_jitterdodge(jitter.width = 0.25, dodge.width = 0.8, seed = 1),
             size = 0.8, alpha = 0.5) +
  geom_pointrange(data = means, aes(y = fit, ymin = lwr, ymax = upr),
                  position = position_dodge(0.8), size = 0.25, linewidth = 0.4) +
  scale_colour_manual(values = water_cols, name = "Water", labels = c("Control", "Drought")) +
  labs(x = NULL, y = expression("Grain yield (t ha"^-1*")")) +
  theme_pub +
  theme(legend.position = "none")


#### Step 8. Put panels together with patchwork ####

fig <- (p_a + p_b) +
  plot_layout(widths = c(1.4, 1)) +
  plot_annotation(tag_levels = "a")

ggsave(file.path(figure_dir, "wheat_figure.pdf"), fig, width = 183, height = 65, units = "mm")
ggsave(file.path(figure_dir, "wheat_figure.png"), fig, width = 183, height = 65, units = "mm", dpi = 600)


#### Try it 1: answer (panel c) ####

fit_r <- glm(rust ~ nitrogen, family = binomial, data = wheat)

new_r <- data.frame(nitrogen = seq(min(wheat$nitrogen), max(wheat$nitrogen), length.out = 100))
pr <- predict(fit_r, newdata = new_r, se.fit = TRUE)   # link (log-odds) scale
new_r$fit <- plogis(pr$fit)
new_r$lwr <- plogis(pr$fit - 1.96 * pr$se.fit)
new_r$upr <- plogis(pr$fit + 1.96 * pr$se.fit)

p_c <- ggplot(wheat, aes(nitrogen, rust)) +
  geom_ribbon(data = new_r, aes(y = fit, ymin = lwr, ymax = upr),
              fill = "grey70", alpha = 0.5) +
  geom_jitter(height = 0.03, width = 0, size = 0.8, alpha = 0.5) +
  geom_line(data = new_r, aes(y = fit), linewidth = 0.4) +
  scale_y_continuous(breaks = c(0, 0.5, 1)) +
  labs(x = expression("Nitrogen (kg ha"^-1*")"), y = "Rust (probability)") +
  theme_pub

fig3 <- (p_a + p_b + p_c) +
  plot_layout(widths = c(1.4, 1, 1)) +
  plot_annotation(tag_levels = "a")
ggsave(file.path(figure_dir, "wheat_figure_3panel.png"), fig3, width = 183, height = 60, units = "mm", dpi = 600)


#### Preview: other packages worth knowing ####

# install.packages(c("cowplot", "ggrepel"))
library(cowplot)
library(ggrepel)

# ggrepel: label points without the labels overlapping (the 5 highest-yielding plots)
top5 <- wheat[order(-wheat$yield), ][1:5, ]
p_repel <- ggplot(wheat, aes(nitrogen, yield)) +
  geom_point(size = 0.8, colour = "grey60") +
  geom_point(data = top5, size = 1) +
  geom_text_repel(data = top5, aes(label = paste("plot", plot)),
                  size = 5 / .pt, family = "Helvetica", seed = 1) +
  theme_pub

# viridis: colour-blind-safe colours for a continuous variable (built into ggplot2)
p_viridis <- ggplot(wheat, aes(nitrogen, yield, colour = aphids)) +
  geom_point(size = 1) +
  scale_colour_viridis_c(name = "Aphids") +
  theme_pub

# scales: axis labels as percentages (also commas, dollars, dates)
p_scales <- p_c + scale_y_continuous(labels = scales::percent, breaks = c(0, 0.5, 1))

# cowplot: plot_grid() is another way to put panels together, with labels
plot_grid(p_repel, p_viridis, p_scales, nrow = 1,
          labels = c("a", "b", "c"), label_size = 8, rel_widths = c(1, 1.25, 1))
