2024

Faceting with ggplot2

  • Faceting creates multiple plots based on the data’s subsets, allowing for easy comparisons.

  • ggplot2 offers two main functions for faceting: facet_wrap() and facet_grid().

Why Use Faceting?

  • Compare different subsets of your dataset within the same visual context.

  • Identify patterns, trends, and outliers across groups more easily.

The facet_wrap() Function

  • facet_wrap() arranges plots in a specified number of rows or columns, wrapping around to create a compact layout.
library(ggplot2)
ggplot(mpg, aes(x = displ, y = hwy)) + 
  geom_point(aes(color = class)) + 
  facet_wrap(~ class)

The facet_wrap() Function

Customizing facet_wrap()

  • You can customize the layout with nrow or ncol and control the scales with scales argument.
ggplot(mpg, aes(x = displ, y = hwy)) + 
  geom_point(aes(color = class)) + 
  facet_wrap(~ class, nrow = 2, scales = "free_y")

Customizing facet_wrap()

The facet_grid() Function

  • facet_grid() arranges plots in a grid based on the values of one or two variables.
ggplot(mpg, aes(x = displ, y = hwy)) + 
  geom_point(aes(color = class)) + 
  facet_grid(rows = vars(drv), cols = vars(cyl))

The facet_grid() Function

Customizing facet_grid()

  • Use the scales argument to control whether scales are shared across the grid and space to control the spacing of panels.
ggplot(mpg, aes(x = displ, y = hwy)) + 
  geom_point(aes(color = class)) + 
  facet_grid(rows = vars(drv), cols = vars(cyl), scales = "free", space = "free")

Customizing facet_grid()

Question

Use facet_wrap() to create individual scatter plots for each class of vehicle, showing the relationship between displ (engine displacement) and hwy (highway miles per gallon).

Click here for the answer
ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() +
  facet_wrap(~ class)

Question

Modify the previous answer such that the scatter plots are organised into 3 rows with each plot using its own y-axis scale.

Click here for the answer
ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() +
  facet_wrap(~ class, nrow = 3, scales = "free_y")

Question

Construct a ggplot2 command using facet_grid() to create a grid of plots by drv and cyl.

Click here for the answer
ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() +
  facet_grid(drv ~ cyl)

Question

Modify the previous to allow each plot to have its own y-axis.

Click here for the answer
ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() +
  facet_grid(drv ~ cyl, scales = "free_y")