Skip to main content

Publication-Ready Figures in R

Friday, November 20: from the default ggplot to a figure a journal will take

Friday, Nov 20, 12:10–1:00 PM, Asmundson 242: step by step, on your laptop. The default ggplot is fine for looking at your data. It is not what goes in a paper. We’ll take one default plot from the Week 3 wheat trial and fix it one step at a time: size, theme, labels, colour, the model, the groups, the panels, and the file you send to the journal. Bring your laptop, and a figure of your own if you have one.

In class we live-code pub_figures_live.R: open it in RStudio and run it one section at a time. Each section saves a PNG; open it to see the change. This page explains each step, and all of its code is in pub_figures.R.


Step 0. Set up

Install the packages once, in the console (skip any you already have):

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

Then load them and read the wheat trial from Week 3: 90 plots, three varieties, two water treatments, a nitrogen rate, and grain yield (t/ha).

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

Every ggsave() below writes to figure_dir, your Desktop unless you change it, so you can open each file as soon as it’s saved.


Step 1. The default

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

Default ggplot scatter of yield against nitrogen, grey background, pink and teal points, legend on the right

On your screen, in RStudio’s Plots pane, this looks fine. That’s the trap: the Plots pane is big, and a journal column is not.


Step 2. Decide the size first

A journal figure has a fixed width. Many journals (Nature, for example) use 89 mm for one column and 183 mm for the full page width; check the author guidelines of yours. Pick the width before you style anything, and always look at the saved file, not the Plots pane:

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)

Open step2.png on your Desktop.

The same default plot saved at 89 by 60 mm: text is huge, the legend takes a third of the width, the data are squeezed

At its real size, the default text is enormous, the legend eats a third of the width, and the grey background and grid compete with the data. Every step below is judged on the saved file at this size.


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

Make one theme object and reuse it for every panel. base_size = 6 gives 6-point text and the tick labels are 5 pt, the smallest most journals allow (never go below 5). Short ticks, tight margins, and a transparent background so the figure sits on any page or slide.

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)

The plot with theme_classic at 7 pt: white background, black axis lines, no grid, small legend

theme_classic() drops the grey panel and the grid. Grid lines rarely help a reader of a printed figure; if a reader needs exact values, they belong in a table.

Helvetica isn’t installed on most Windows computers. Use base_family = "Arial", which looks almost the same, or leave base_family out and R uses its default sans-serif font.


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

Axis titles are words with units, not column names. expression() writes superscripts (^) and joins pieces (*):

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)

Plot with axis titles Nitrogen (kg ha^-1) and Grain yield (t ha^-1), blue and orange points, small legend inside the top-left corner

The legend now sits inside the empty top-left corner, with a short bold title, so the data get the full width. legend.position.inside is in (x, y) from 0 to 1 across the panel; legend.justification = c(0, 1) pins the legend’s own top-left corner there.


Step 5. Colours everyone can read

About 1 in 12 men has red-green colour blindness, and some readers print in greyscale. The default ggplot colours fail both: the pink and teal are nearly the same grey. Blue and orange is the pair colour-blind readers tell apart most easily, and these two (#4E79A7, #F28E2B) also stay distinct in greyscale.

Two rows of colour swatches. ggplot default pink and teal turn into two similar greys. The blue and orange used here turn into dark and light grey

For more than two groups, the Okabe-Ito palette was designed for colour-blind readers. The eight colours, to copy:

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

R 4.0 and later has them built in, too: palette.colors(palette = "Okabe-Ito"). Two more rules: use the same colour for the same thing in every panel and every figure of a paper, and if two groups must be told apart in greyscale, add shape = as well.


Step 6. Show the model, not just the points

A figure in a results section should show what you fit. Fit the model, predict over a grid with a confidence interval (Week 2), and draw the data, the fitted lines and the 95% CI together:

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)

Yield against nitrogen with a fitted line and shaded 95% confidence band for each water treatment: the control line climbs steeply, the drought line is nearly flat

Now the reader sees the result (nitrogen raises yield much more with water than under drought; the interaction is clear, p < 0.001), and can check it against every plot. show.legend = FALSE on the ribbon keeps the shading out of the legend keys.

Why not geom_smooth(method = "lm")? It fits its own model, separately for each colour. That’s fine for exploring, but in a paper the line should come from the model you report.


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

The bar plot with an error bar (a “dynamite plot”) is everywhere in agricultural papers, and it hides almost everything: how many plots, how they spread, whether one outlier drives the mean. Put the points on the plot, with the model’s mean and 95% CI on top:

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

Left: bar plot of mean yield by variety and water with error bars. Right: the same comparison as individual plots with the mean and 95% CI drawn over them

Same means, but on the right you can see 15 plots per group, the spread, and that drought pulls every variety down to about the same yield. The legend is off here because panel a will carry it (next step), and x = NULL drops an axis title the variety names make obvious.


Step 8. Put panels together with patchwork

patchwork combines saved ggplot objects with arithmetic: + or | side by side, / stacked.

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)

Two-panel figure 183 mm wide. Panel a: yield against nitrogen with fitted lines and confidence bands by water treatment. Panel b: yield by variety and water, points with means and 95% CI

  • tag_levels = "a" adds the bold a, b labels (8 pt, from plot.tag in theme_pub). Use "A" if your journal wants capitals.
  • widths = c(1.4, 1) gives the scatter more room than the three-variety panel.
  • plot_layout(guides = "collect") gathers legends from several panels into one; we didn’t need it, because only panel a has a legend.
  • Patchwork lines up the axes of the panels for you, so the two plotting areas start and end at the same height.

Step 9. Save the right file

  • PDF for the journal. ggsave("figure.pdf", ...) keeps everything as vectors: lines stay sharp at any zoom, and the text stays text (you can select it, and the editor can fix a typo). Submit this unless the journal says otherwise.
  • PNG for slides, Word and the web, at dpi = 600 (300 at least). Never paste a screenshot of the Plots pane.
  • Set width, height and units every time. Without them, ggsave() uses the size of your Plots pane, which changes every time you drag it.
  • Save the code, not the picture. The script that makes the figure is the figure. When a reviewer asks for a change, you rerun one line.

Before you send it, check:


NoteTry it 1

Add a panel c: the probability of rust against nitrogen, from a logistic GLM (Week 3: glm(rust ~ nitrogen, family = binomial, data = wheat)). Show the 0/1 data, the fitted curve and its 95% CI, and make a three-panel figure 183 mm wide.

Hint: predict on the link scale with se.fit = TRUE, build the interval there (fit ± 1.96 × se.fit), then turn everything into probabilities with plogis().

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)

Three-panel figure: a, yield against nitrogen by water; b, yield by variety and water; c, rust probability rising with nitrogen, with 0/1 points jittered at the top and bottom

Rust becomes more likely with more nitrogen (p < 0.001). The interval is built on the log-odds scale and then transformed, so it never goes below 0 or above 1. geom_jitter(height = 0.03, width = 0) spreads the 0s and 1s a little vertically so overlapping plots don’t hide each other, without moving their nitrogen values. Panel c is grey because water isn’t in this model: colour only where it means something.

NoteTry it 2

Take a figure from one of your problem sets (or your own research) and run it through the checklist in Step 9. Save it at 89 mm wide and look at the file. What did you have to change?


Preview: other packages worth knowing

Section 9 of the live script. One example each, on the same wheat data:

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

Three panels assembled with cowplot: a, yield against nitrogen with the five highest-yielding plots labelled by ggrepel; b, points coloured by aphid count on the viridis scale; c, rust probability with the y axis in percent

Package What it’s for
patchwork Combining panels with +, |, / (what we used)
cowplot Combining panels with plot_grid(); also ggdraw() to put an image or a plot inset on top of another
ggrepel Text labels that move out of each other’s way
viridis scales scale_colour_viridis_c() / _d(): colour-blind-safe, prints well in greyscale
scales Axis label formats: percent, comma, dollar, label_log()
ggpubr Ready-made publication-style plots and ggarrange() for panels
gridExtra grid.arrange(): the older way to arrange plots; you’ll see it in old code

patchwork and cowplot do the same job; pick one and stick to it.


Troubleshooting

Click a tip to open it.

Patchwork isn’t loaded. Run library(patchwork); if that says there is no package called ‘patchwork’, install it first with install.packages("patchwork").

legend.position = "inside" and legend.position.inside arrived in ggplot2 3.5.0. Check with packageVersion("ggplot2"), and update with install.packages("ggplot2") (then restart R). On an older version, legend.position = c(0.04, 0.94) does the same thing.

That’s expected: the Plots pane is a different size. Text is set in points, which are a fixed physical size, so a smaller page means relatively bigger text. Judge the saved file, at its real size, never the Plots pane.

Run figure_dir to see the folder R is saving to, and dir.exists(figure_dir) to check it exists. Set it to any folder you like, written out in full on Windows: figure_dir <- "C:/Users/yourname/Desktop" (with OneDrive it may be "C:/Users/yourname/OneDrive/Desktop").

Without a plot argument, ggsave() saves the last plot you displayed. Always name it: ggsave("figure.pdf", fig, ...).

R’s standard pdf() device uses Helvetica as one of the built-in PDF fonts and doesn’t embed it, which most journals accept. If yours insists, save with device = cairo_pdf, which embeds the fonts. On a Mac, cairo_pdf needs XQuartz installed (free, from xquartz.org); without it you get “failed to load cairo DLL”.

Make them smaller (size = 0.8) and partly transparent (alpha = 0.5), so dense areas look darker. With thousands of points, geom_hex() or geom_bin2d() show density instead of individual points.


Extra resources