How to Use facet_wrap in ggplot2 for Plot Faceting
Use
facet_wrap(~ variable) in ggplot2 to create multiple plots (facets) based on the unique values of a variable. It arranges these plots in a grid, making it easy to compare subsets of data side by side.Syntax
The basic syntax of facet_wrap is:
facet_wrap(~ variable): creates facets based on the unique values ofvariable.nrowandncol: control the number of rows and columns in the facet grid.scales: controls if axes are fixed ("fixed") or free ("free","free_x","free_y") across facets.
r
facet_wrap(~ variable, nrow = NULL, ncol = NULL, scales = "fixed")Example
This example shows how to use facet_wrap to create separate scatter plots of mpg vs wt for each number of cylinders in the mtcars dataset.
r
library(ggplot2) ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + facet_wrap(~ cyl, nrow = 1) + labs(title = "MPG vs Weight by Cylinder Count", x = "Weight", y = "Miles per Gallon")
Output
[A plot window opens showing three scatter plots side by side, each labeled with the number of cylinders (4, 6, 8). Each plot shows points of mpg vs wt for cars with that cylinder count.]
Common Pitfalls
- Forgetting the tilde
~before the variable insidefacet_wrapcauses an error. - Using
facet_wrapwith continuous variables without converting them to factors can produce many unwanted facets. - Not setting
scalesproperly can make comparisons hard if axes differ unexpectedly.
r
## Wrong: missing tilde # ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(cyl) ## Right: ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~ cyl)
Quick Reference
- ~ variable: variable to facet by
- nrow, ncol: number of rows or columns in the facet grid
- scales: "fixed" (default), "free", "free_x", or "free_y" to control axis scales
- strip.position: position of facet labels ("top", "bottom", "left", "right")
Key Takeaways
Use facet_wrap(~ variable) to split plots by unique values of a variable.
Always include the tilde (~) before the variable inside facet_wrap.
Control layout with nrow and ncol to arrange facets in rows or columns.
Set scales to "free" if you want axes to vary between facets.
Convert continuous variables to factors before faceting to avoid too many plots.