Faceting

Colour and shape aesthetics let you show a categorical variable within one panel. Faceting takes a different approach: it splits your data into separate panels, one per category (or combination of categories), all drawn with the same axes so panels are directly comparable.

Faceting on one variable: facet_wrap()

Do: run the code below.

See: instead of one crowded scatterplot with colour-coded classes, you get one small scatterplot per vehicle class, arranged in a 2-row grid.

Predict: what do you think nrow = 2 controls? What happens if you change it to nrow = 4?

Explain: nrow (and its counterpart ncol) simply controls how the same set of panels is arranged in rows and columns. It doesn’t change which data goes in which panel, only the layout of the panels on the page.

Note

facet_wrap() accepts either a one-sided formula (~ class) or the tidy-eval style vars(class), you’ll see both in the wild: facet_wrap(~ class) and facet_wrap(vars(class)) do exactly the same thing.

Faceting on two variables: facet_grid()

Do: run this example, which facets on both drv and cyl at once.

See: a grid of panels appears, with one row per level of drv and one column per level of cyl. Some panels are completely empty.

Predict: what do you think an empty panel, for example, rear-wheel drive (drv = "r") combined with 4 cylinders, actually means?

Explain: an empty panel means there are simply no cars in the dataset with that exact combination of drive train and cylinder count (e.g., no rear-wheel-drive cars with 4 cylinders appear in mpg). facet_grid() still reserves space for every combination of the two faceting variables, even if some combinations have zero observations. This is a useful way to notice gaps in your data.

Practice exercise

Build a scatterplot of displ (x-axis) against hwy (y-axis), then facet by manufacturer using facet_wrap(). Also add proper axis labels with labs(). Predict roughly how many panels you’ll get before running the code.

Try nrow = 3 to keep the panels a reasonable size, and remember unique(mpg$manufacturer) if you want to check the number of levels first.

ggplot(mpg) +
  geom_point(aes(x = displ, y = hwy)) +
  labs(
    x = "Engine displacement (litres)",
    y = "Highway miles per gallon"
  ) +
  facet_wrap(~ manufacturer, nrow = 3)

There are 15 manufacturers in mpg, so you get 15 panels.

Back to top