Graphics Reference
In-Depth Information
Chapter11.Facets
One of the most useful techniques in data visualization is rendering groups of data alongside each
other, making it easy to compare the groups. With ggplot2, one way to do this is by mapping a
discrete variable to an aesthetic, like xposition, color, or shape. Another way of doing this is to
create a subplot for each group and draw the subplots side by side.
These kinds of plots are known as Trellisdisplays. They're implemented in the lattice package as
well as in the ggplot2 package. In ggplot2, they're called facets. In this chapter I'll explain how
to use them.
Splitting Data into Subplots with Facets
Problem
You want to plot subsets of your data in separate panels.
Solution
Use facet_grid() or facet_wrap() , and specify the variables on which to split.
With facet_grid() , you can specify a variable to split the data into vertical subpanels, and an-
other variable to split it into horizontal subpanels ( Figure 11-1 ):
# The base plot
p <- ggplot(mpg, aes(x = displ, y = hwy)) + geom_point()
# Faceted by drv, in vertically arranged subpanels
p + facet_grid(drv ~ . )
# Faceted by cyl, in horizontally arranged subpanels
p + facet_grid( . ~ cyl)
# Split by drv (vertical) and cyl (horizontal)
p + facet_grid(drv ~ cyl)
Search WWH ::




Custom Search