facet_wrap() Basics
You'll learn how to automatically create a grid of similar plots, each showing a different subset of your data based on one categorical variable.
What Are Facets in Practice?
After understanding the concept of small multiples, it's time to actually create them. facet_wrap() is ggplot2's workhorse function for splitting your data into separate panels based on the unique values of a categorical variable. Think of it like dealing cards from a deck—ggplot2 takes your dataset, separates it by category, and lays out individual plots in a flexible grid arrangement.
How facet_wrap() Works
The basic syntax is simple: you add facet_wrap(~ variable_name) to your ggplot object. The tilde (~) is formula syntax meaning "facet by this variable." ggplot2 will create one panel for each unique value in that variable and arrange them in rows and columns automatically.
ggplot(data, aes(x = numeric_var, y = another_var)) +
geom_point() +
facet_wrap(~ category_var)
This code creates a scatter plot for each level of category_var, automatically wrapping panels into a grid layout.
Flexible Layout Control
Unlike a rigid grid system, facet_wrap() intelligently fills available space. You can control the number of rows or columns using nrow or ncol parameters:
facet_wrap(~ category_var, ncol = 3)
This forces the panels into exactly 3 columns, letting the rows expand as needed.
Why Use facet_wrap()?
It's perfect when you want to compare patterns across groups without cluttering a single plot with overlapping data. Each facet shares the same scales (by default), making visual comparison intuitive and immediate.
Key Takeaway: facet_wrap() automatically splits your data by one categorical variable into a flexible grid of small multiples, making group comparisons clear and efficient.