# Saving publication-quality ggplot figures with ggsave
# https://tidyecology.com/posts/publication-quality-ggplot-figures/
#
# 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-11-05

## ---- figure ----
library(ggplot2)

set.seed(7)
elev <- runif(120, 200, 2600)
rich <- rpois(120, exp(1.4 + 1.7 * exp(-((elev - 1300) / 600)^2)))
df <- data.frame(elev, rich)

p <- ggplot(df, aes(elev, rich)) +
  geom_point(color = "#2f6d54", alpha = 0.75, size = 2) +
  geom_smooth(method = "loess", formula = y ~ x, se = TRUE,
              color = "#1d5b4e", fill = "#cfe0d4", linewidth = 0.9) +
  labs(x = "Elevation (m)", y = "Species richness",
       title = "Species richness peaks at mid elevation") +
  theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color = "#dad9ca", linewidth = 0.3),
        plot.title = element_text(face = "bold", color = "#16241d"))
p

## ---- resolution ----
out <- tempdir()
ggsave(file.path(out, "fig_300.png"), p, width = 85, height = 85, units = "mm", dpi = 300)
ggsave(file.path(out, "fig_600.png"), p, width = 85, height = 85, units = "mm", dpi = 600)

png_dim <- function(f) {                       # read width and height from the PNG header
  x <- readBin(f, "integer", n = 6, size = 4, endian = "big")
  c(width = x[5], height = x[6])
}
rbind(`300 dpi` = png_dim(file.path(out, "fig_300.png")),
      `600 dpi` = png_dim(file.path(out, "fig_600.png")))

## ---- vector ----
# cairo_pdf embeds and subsets the fonts; fall back if this R was built without cairo
pdf_device <- if (isTRUE(capabilities("cairo"))) cairo_pdf else pdf
ggsave(file.path(out, "fig.pdf"), p, width = 85, height = 85, units = "mm",
       device = pdf_device)
ggsave(file.path(out, "fig.svg"), p, width = 85, height = 85, units = "mm")
ggsave(file.path(out, "fig.tiff"), p, width = 85, height = 85, units = "mm",
       dpi = 300, compression = "lzw")

files <- c("fig_300.png", "fig.tiff", "fig.pdf", "fig.svg")
data.frame(file = files,
           kb = round(file.size(file.path(out, files)) / 1024, 1))

## ---- recipe ----
save_fig <- function(plot, name, width = 85, height = 85, dpi = 300) {
  ggsave(paste0(name, ".pdf"), plot, width = width, height = height,
         units = "mm", device = cairo_pdf)                       # vector master
  ggsave(paste0(name, ".png"), plot, width = width, height = height,
         units = "mm", dpi = dpi)                                 # raster preview
  invisible(name)
}
# save_fig(p, file.path(tempdir(), "richness_elevation"), width = 170)
