Compound figures
Introduction
In this worksheet, we will discuss how to combine several ggplot2 plots into one compound figure.
First we need to load the required R packages. Please wait a moment until the live R session is fully set up and all packages are loaded.
We will be working with the R builtin dataset mtcars
, which contains fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models).
Combining plots
First we set up four different plots that we will subsequently combine. The plots are stored in variables p1
, p2
, p3
, p4
.
To show plots side-by-side, the patchwork package provides the operator |
, as in p1 | p2
. Try this by making a compound plot of plots p1
, p2
, p3
side-by-side.
| p2 | p3 p1
To show plots on top of one-another, we use the operator /
, as in p1 / p2
. Try this by making a compound plot of plots p1
, p2
, p3
on top of each other.
/ p2 / p3 p1
We can also use parentheses to group plots with respect to the operators |
and /
. For example, we can place several plots side-by-side and then place this entire row of plots on top of another plot. Try this out.
/ p4 (___)
| p2 | p3 ) / p4 (p1
Plot annotations
The patchwork package provides a powerful annotation system via the plot_annotation()
function that can be added to a plot assembly. For example, we can add plot tags (the labels in the upper left corner identifying the plots) via the plot annotation tag_levels
. You can set tag_levels = "A"
to generate tags A, B, C, etc. Try this out.
| p2 | p3 ) / p4 +
(p1 plot_annotation(
___ )
| p2 | p3 ) / p4 +
(p1 plot_annotation(
tag_levels = "A"
)
Try also tag levels such as "a"
, "i"
, or "1"
.
You can also add elements such as titles, subtitles, and captions, by setting the title
, subtitle
, or caption
argument in plot_annotation()
. Try this out by adding an overall title to the figure from the previous exercise.
| p2 | p3 ) / p4 +
(p1 plot_annotation(
tag_levels = "A",
___ )
| p2 | p3 ) / p4 +
(p1 plot_annotation(
tag_levels = "A",
title = "Various observations about old cars"
)
Also set a subtitle and a caption.
Finally, you can change the theme of all plots in the plot assembly via the &
operator, as in (p1 | p2) & theme_bw()
. Try this out.
| p2) & theme_bw() (p1
What happens if you write this expression without parentheses? Do you understand why?