facet_grid() for Two Variables
You'll learn how to create a grid of plots where rows and columns represent two different categorical variables.
In the previous lesson, you used facet_wrap() to split your data by one variable. Now, facet_grid() takes this further by letting you organize subplots in a matrix layout based on two categorical variables simultaneously—one defining the rows, the other defining the columns.
Think of it like a multiplication table: instead of numbers, each cell contains a plot filtered by the combination of row and column categories.
The Syntax
The key difference is the formula notation:
ggplot(data, aes(x = var1, y = var2)) +
geom_point() +
facet_grid(rows ~ cols)
rows: The variable that splits plots into rows (vertical organization)cols: The variable that splits plots into columns (horizontal organization)- The
~(tilde) separates them
Example Structure
# Each combination of drv (4wd, fwd, rwd) and cyl (4, 6, 8) gets its own panel
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_grid(drv ~ cyl)
This creates a grid where:
- Each row represents a drive type (drv)
- Each column represents cylinder count (cyl)
- You can instantly compare patterns across both dimensions
When to Use It
Use facet_grid() when you want to systematically compare how two categorical variables jointly affect your data. It's perfect for controlled comparisons where the grid structure itself is meaningful.
Key Takeaway: facet_grid(rows ~ cols) creates a matrix of plots organized by two categorical variables, enabling systematic comparisons across both dimensions simultaneously.