Plotting with ggplot2

R · Practical · 15 min

ggplot2 is the standard for clear, publication-quality graphics in R.

ggplot2 implements the grammar of graphics: a plot is data plus mappings from columns to visual properties, drawn by geometric layers.

  • ggplot(df, aes(x = wt, y = mpg)) sets the data and default aesthetics (x, y, colour, fill, size, shape).
  • Add layers with +: geom_point(), geom_line(), geom_col() (bar heights from data), geom_bar() (counts), geom_histogram(), geom_boxplot(), geom_smooth(method = "lm").
  • facet_wrap(~ cyl) splits into small multiples.
  • labs(title =, x =, y =) sets labels, scale_* functions control axes and colours, and theme_minimal() and friends change the look.

Mapping versus setting is the classic confusion: aes(colour = factor(cyl)) maps a column to colour and adds a legend, while geom_point(colour = "blue") outside aes sets a constant.

ggplot2 wants long data: one row per observation, one column per variable. If you find yourself adding one geom_line per series, reshape with tidyr::pivot_longer and map the series name to colour instead.

Save with ggsave("plot.png", p, width = 6, height = 4, dpi = 300). Inside scripts and functions, a plot only appears when printed, so call print(p).

Example

library(ggplot2)

p <- ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) +
  geom_point(size = 2) +
  geom_smooth(method = "lm", se = FALSE, formula = y ~ x) +
  facet_wrap(~ am, labeller = label_both) +
  labs(title = "Fuel economy vs weight", x = "Weight (1000 lb)",
       y = "Miles per gallon", colour = "Cylinders") +
  theme_minimal()

out <- tempfile(fileext = ".png")
ggsave(out, p, width = 7, height = 4, dpi = 100)
print(file.exists(out))          #> [1] TRUE
print(length(p$layers))          #> [1] 2

Remember

  • A plot = data + aes() mappings + geom layers added with +
  • Inside aes() maps a column; outside sets a constant
  • Reshape to long data instead of one layer per series
  • ggsave writes files; print(p) shows plots inside scripts

Watch out for

  • Writing aes(colour = "blue"), which maps the constant string as a category and adds a legend.

Check yourself

  1. You want all points red. Which is correct?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: ggplot2.tidyverse.org/reference/index.html

Builds on

Unlocks

Nothing builds on this yet.

Plotting with ggplot2 · R · Topolearn