Skip to Content
R Graphics Cookbook, 2nd Edition
book

R Graphics Cookbook, 2nd Edition

by Winston Chang
November 2018
Beginner to intermediate content levelBeginner to intermediate
441 pages
9h 25m
English
O'Reilly Media, Inc.
Content preview from R Graphics Cookbook, 2nd Edition

Chapter 11. 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 x position, colour, 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 Trellis displays. 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.

11.1 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 another variable to split it into horizontal subpanels (Figure 11-1):

# Create the base plot
mpg_plot <- ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point()

# Faceted by drv, in vertically arranged subpanels
mpg_plot +
  facet_grid(drv ~ .)

# Faceted by cyl, in horizontally arranged subpanels
mpg_plot +
  facet_grid(. ~ cyl)

# Split by drv (vertical) and cyl (horizontal)
mpg_plot +
  facet_grid(drv ~ cyl)
Faceting horizontally by drv (top); Faceting vertically by cyl (middle); Faceting in both directions, with both variables (bottom)
Figure 11-1. Faceting horizontally by cyl (top); faceting vertically by dev (left); faceting in both directions, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

R Graphics Cookbook

R Graphics Cookbook

Winston Chang
R Cookbook, 2nd Edition

R Cookbook, 2nd Edition

JD Long, Paul Teetor
R Statistics Cookbook

R Statistics Cookbook

Francisco Juretig

Publisher Resources

ISBN: 9781491978597Errata Page