Home » How to Use facet_wrap in R (With Examples)

How to Use facet_wrap in R (With Examples)

by Tutor Aspire

The facet_wrap() function can be used to produce multi-panel plots in ggplot2.

This function uses the following basic syntax:

library(ggplot2)

ggplot(df, aes(x_var, y_var)) +
  geom_point() +
  facet_wrap(vars(category_var))

The following examples show how to use this function with the built-in mpg dataset in R:

#view first six rows of mpg dataset
head(mpg)

manufacturer  model  displ  year  cyl	     trans  drv	cty  hwy  fl	  class
										
audi	         a4    1.8  1999    4	auto(l5)      f	18    29   p	compact
audi	         a4    1.8  1999    4	manual(m5)    f	21    29   p	compact
audi	         a4    2.0  2008    4	manual(m6)    f	20    31   p	compact
audi	         a4    2.0  2008    4	auto(av)      f	21    30   p	compact
audi	         a4    2.8  1999    6	auto(l5)      f	16    26   p	compact
audi	         a4    2.8  1999    6	manual(m5)    f	18    26   p	compact

Example 1: Basic facet_wrap() Function

The following code shows how to create several scatterplots in ggplot2 using displ as the x-axis variable, hwy as the y-axis variable, and class as the grouping variable:

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(vars(class))

Example 2: Use Custom Labels

The following code shows how to use the facet_wrap() function with custom labels for the plot titles:

#define custom labels
plot_names #use facet_wrap with custom plot labels
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(vars(class), labeller = as_labeller(plot_names))

facet_wrap with custom labels in R

Example 3: Use Custom Scales

The following code shows how to use the facet_wrap() function with custom scales for each individual plot:

#use facet_wrap with custom scales
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(vars(class), scales='free')

Example 4: Use Custom Order

The following code shows how to use the facet_wrap() function with a custom order for the individual plots:

#define order for plots
mpg compact', '2seater', 'suv',
                                                   'subcompact', 'pickup',
                                                   'minivan', 'midsize')))

#use facet_wrap with custom order
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(vars(class))

face_wrap() with custom order in R

Notice that the plots appear in the exact order that we specified.

Additional Resources

How to Change Font Size in ggplot2
How to Remove a Legend in ggplot2
How to Rotate Axis Labels in ggplot2

You may also like