Faceting creates multiple plots based on the data’s subsets, allowing for easy comparisons.
ggplot2 offers two main functions for faceting:
facet_wrap()
andfacet_grid()
.
2024
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()
.
Compare different subsets of your dataset within the same visual context.
Identify patterns, trends, and outliers across groups more easily.
facet_wrap()
Functionfacet_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)
facet_wrap()
Functionfacet_wrap()
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")
facet_wrap()
facet_grid()
Functionfacet_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))
facet_grid()
Functionfacet_grid()
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")
facet_grid()
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).
ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + facet_wrap(~ class)
Modify the previous answer such that the scatter plots are organised into 3 rows with each plot using its own y-axis scale.
ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + facet_wrap(~ class, nrow = 3, scales = "free_y")
Construct a ggplot2 command using facet_grid()
to create a grid of plots by drv
and cyl
.
ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + facet_grid(drv ~ cyl)
Modify the previous to allow each plot to have its own y-axis.
ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + facet_grid(drv ~ cyl, scales = "free_y")