2.8 Facets
Facets are ways of grouping a data plot into multiple different pieces (subplots). This allows you to view a separate plot for each value in a categorical variable. You can construct a plot with multiple facets by using the facet_wrap()
function. This will produce a “row” of subplots, one for each categorical variable (the number of rows can be specified with an additional argument):
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_grid(~ class)
You can also facet_grid
to facet your data by more than one categorical variable. Note that we use a tilde (~
) in our facet
functions. With facet_grid
the variable to the left of the tilde will be represented in the rows and the variable to the right will be represented across the columns.
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_grid(year ~ cyl)