Faceting helps you split one big plot into smaller plots based on categories. It makes it easier to compare groups side by side.
0
0
Faceting for subplots in R Programming
Introduction
You want to compare sales data for different regions in separate small plots.
You have survey results for different age groups and want to see each group's pattern.
You want to show how a variable changes over time for different categories.
You want to display multiple subsets of data clearly without mixing them in one plot.
Syntax
R Programming
ggplot(data) +
geom_point(mapping) +
facet_wrap(~ variable)
# or
ggplot(data) +
geom_point(mapping) +
facet_grid(rows ~ cols)facet_wrap() creates subplots wrapped into multiple rows or columns.
facet_grid() arranges subplots in a grid with rows and columns based on variables.
Examples
This makes small plots for each car class side by side.
R Programming
ggplot(mpg) +
geom_point(aes(displ, hwy)) +
facet_wrap(~ class)This creates a grid of plots with drv as rows and cyl as columns.
R Programming
ggplot(mpg) + geom_point(aes(displ, hwy)) + facet_grid(drv ~ cyl)
Sample Program
This program shows how engine size relates to highway fuel efficiency for each car class in separate small plots.
R Programming
library(ggplot2) # Use the built-in mpg dataset # Plot engine displacement vs highway miles per gallon # Facet by car class ggplot(mpg) + geom_point(aes(displ, hwy)) + facet_wrap(~ class) + labs(title = "Engine Size vs Highway MPG by Car Class")
OutputSuccess
Important Notes
Faceting automatically shares axes by default, making comparison easier.
You can control the number of rows or columns in facet_wrap() with nrow or ncol.
Use scales = "free" inside faceting functions to allow axes to vary per subplot.
Summary
Faceting splits one plot into many small plots based on categories.
facet_wrap() arranges plots wrapped in rows or columns.
facet_grid() arranges plots in a grid by rows and columns.