Labels & Themes

A plot with correct data but no labels is hard to interpret. In the last topic of this tutorial, we focus on polishing a plot so it’s understandable by others.

Adding labels

Do: start from the scatterplot you built earlier and run the code below.

See: the axes are labelled with the raw variable names (displ, hwy), and the legend is labelled class. This might be fine for you, but not very informative for someone unfamiliar with the dataset.

Predict: what do you think each argument in the labs() call below controls?

Explain: labs() lets you rename any labelled element of the plot: axis titles, the legend title, and an overall title (or subtitle/caption). by supplying arguments that match the aesthetic or role you want to relabel.

Note

xlab(), ylab(), and ggtitle() do the same job as labs(x = ...), labs(y = ...), and labs(title = ...) respectively, you’ll see both styles used in practice.

Applying a theme

The theme controls all of the non-data ink in a plot: background colour, gridlines, font, etc. The ggplot2 package includes several ready-made themes.

Just like with anything in R, we can store ggplots as objects and reuse them. Here we store our base plot in an object called p, so we can add different themes to it without rebuilding the plot each time.

Do: run each of the following and compare.

Predict: which theme do you think would work best for a plot to include in a report, and why?

Explain: each theme changes the same underlying plot. The data, points, and colours stay identical, only the non-data elements change. theme_bw() and theme_classic() add solid borders and are often preferred for print, while theme_minimal() drops borders. theme_classic() also drops gridlines. Choosing a theme is a matter of what you want to emphasize and where the plot will be used, it will not change the underlying data or statistics.

Practice exercise

Using the mpg data:

  1. Build a scatterplot of hwy (y-axis) against cty (x-axis), mapping drv to colour.
  2. Add axis labels: "City miles per gallon" and "Highway miles per gallon".
  3. Give the legend the title "Drive train".
  4. Apply theme_minimal().

You’ll need one geom_point() layer, one labs() layer (with three arguments), and one theme layer.

ggplot(data = mpg, mapping = aes(x = cty, y = hwy, colour = drv)) +
  geom_point() +
  labs(
    x = "City miles per gallon",
    y = "Highway miles per gallon",
    colour = "Drive train"
  ) +
  theme_minimal()

You’ve now built a complete plot from scratch: data, mapping, geometry, labels, and theme. Continue with the knowledge quiz.

Back to top