14.8 Combining Several Plots into the Same Graphic
14.8.2 Solution
The patchwork package can be used to combine several ggplot2 plots into one graphic. (Figure 14.6).
library(patchwork)
ggplot(PlantGrowth, aes(x = weight)) +
plot1 <- geom_histogram(bins = 12)
ggplot(PlantGrowth, aes(x = group, y = weight, group = group)) +
plot2 <- geom_boxplot()
+ plot2 plot1
14.8.3 Discussion
Patchwork also allows you to determine how you want to lay out the ggplots in relation to each other, by adding a plot_layout()
call. You can use this call to determine the number of columns you want the pplots to be arranged in (Figure 14.7), and the size of the plots (Figure 14.8):
ggplot(PlantGrowth, aes(x = weight, fill = group)) +
plot3 <- geom_density(alpha = 0.25)
+ plot2 + plot3 +
plot1 plot_layout(ncol = 2)
+ plot2 +
plot1 plot_layout(ncol = 1, heights = c(1, 4))
In the future, patchwork may be available on CRAN, in which case it can be installed using the usual install.packages()
.
14.8.4 See Also
For more on additional patchwork features, see https://github.com/thomasp85/patchwork.