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

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

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

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


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

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

# Save it at one journal column wide (89 mm) and open the file
ggsave(file.path(figure_dir, "fig_1_default.png"), p, width = 89, height = 60, units = "mm", dpi = 600)


#### 2. Theme: 6 pt text, 5 pt tick labels, no grey background ####

theme_pub <- theme_classic(base_size = 6, base_family = "Helvetica") +   # Windows: "Arial"
  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, "fig_2_theme.png"), p, width = 89, height = 60, units = "mm", dpi = 600)


#### 3. Labels with units, legend inside the panel ####

p <- p +
  labs(x = expression("Nitrogen (kg ha"^-1*")"),
       y = expression("Grain yield (t ha"^-1*")")) +
  theme(legend.position = "inside",
        legend.position.inside = c(0.04, 0.94),
        legend.justification = c(0, 1))
ggsave(file.path(figure_dir, "fig_3_labels.png"), p, width = 89, height = 60, units = "mm", dpi = 600)


#### 4. Colour-blind-safe colours: blue and orange ####

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

p <- p + scale_colour_manual(values = water_cols, name = "Water", labels = c("Control", "Drought"))
ggsave(file.path(figure_dir, "fig_4_colours.png"), p, width = 89, height = 60, units = "mm", dpi = 600)


#### 5. Show the model: fitted lines + 95% CI ####

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

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"))
head(new)

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, "fig_5_model.png"), p_a, width = 89, height = 60, units = "mm", dpi = 600)


#### 6. Groups: points + mean and CI, not bars ####

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"))
means

# The bar plot, for comparison
ggplot(means, aes(variety, fit, fill = water)) +
  geom_col(position = position_dodge(0.8), width = 0.7) +
  geom_errorbar(aes(ymin = fit, ymax = upr), position = position_dodge(0.8), width = 0.2)

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) +
  labs(x = NULL, y = expression("Grain yield (t ha"^-1*")")) +
  theme_pub +
  theme(legend.position = "none")
ggsave(file.path(figure_dir, "fig_6_groups.png"), p_b, width = 60, height = 60, units = "mm", dpi = 600)


#### 7. Two panels with patchwork, saved for the journal ####

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")             # journal
ggsave(file.path(figure_dir, "wheat_figure.png"), fig, width = 183, height = 65, units = "mm", dpi = 600)  # slides, Word


#### 8. Your turn: panel c, rust probability against nitrogen ####

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

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)   # 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)


#### 9. A preview of other packages ####

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

# ggrepel: label points without the labels overlapping (here, 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) +
  labs(x = expression("Nitrogen (kg ha"^-1*")"),
       y = expression("Grain yield (t ha"^-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") +
  labs(x = expression("Nitrogen (kg ha"^-1*")"),
       y = expression("Grain yield (t ha"^-1*")")) +
  theme_pub

# scales: axis labels as percentages (or commas, dollars, dates...)
p_scales <- p_c +
  scale_y_continuous(labels = scales::percent, breaks = c(0, 0.5, 1)) +
  labs(y = "Rust")

# cowplot: plot_grid() is another way to put panels together, with labels
fig_cow <- 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))
ggsave(file.path(figure_dir, "fig_9_preview.png"), fig_cow, width = 183, height = 60, units = "mm", dpi = 600)
