Sometimes you simply want to put multiple plots side by side and call it a day, but often you want the end result to stand forth like a collective thing. To achieve that you would often add a title and other textual cues. This guide will teach you how to do that.
As always, we start with some plots.
library(ggplot2) p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp)) + ggtitle('Plot 1') p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear)) + ggtitle('Plot 2') p3 <- ggplot(mtcars) + geom_point(aes(hp, wt, colour = mpg)) + ggtitle('Plot 3') p4 <- ggplot(mtcars) + geom_bar(aes(gear)) + facet_wrap(~cyl) + ggtitle('Plot 4')
Often, especially in scientific literature, multiple plots are collected in a single figure and referred to by a tag. While such tags could be added manually, it is much simpler to let patchwork handle it for you, using the auto-tagging functionality. This is turned on by setting
plot_annotation() to a value indicating the family of symbols to use for tagging:
'1' for Arabic numerals,
'A' for uppercase Latin letters,
'a' for lowercase Latin letters,
'I' for uppercase Roman numerals, and
'i' for lowercase Roman numerals.
When the patchwork contains nested layouts the tagging will recurse into them by default, but you can tell it to define a new tagging level with the
tag_level argument in
plot_layout(). You can then provide multiple tag-types to
tag_levels to define how subtagging should be enumerated.
plot_annotation()it is also possible to define separator, prefix, and suffix for the tag, but don’t go overboard with it:
The default ggplot2 theme puts the tag in its own row and column that will expand to fit. For longer tag text this will look weird, so it is better to place it on top of the plot region:
Most of the style of the patchwork is made up by the themes of the individual patches. For a coherent look, don’t mix videly different looks. Setting the background colour of a single plot to a different shade is an effective way to highlight it, but e.g. different fonts or line widths will just look like a mess. The patchwork itself has a few elements itself that is succeptible to theming: A background, a margin, and title, subtitle & caption. The theme of the patchwork is by default the default ggplot2 theme. It can be changed though, in two different ways. The easiest is to simply use
& with a theme element. This operator will add to the theme of all subplots as well as to the theme of the patchwork itself:
If you need to address only the theme of the patchwork itself (e.g. for making the patchwork title larger than the plot titles), it can be done with the
theme argument in
plot_annotation() (note that the use of one does not exclude the other):