Arranging plots in R with the patchwork package

The patchwork package in R allows you to customise the arrangement of your graphs. In the following video I work through a number of examples. The code and examples from the video are also provided below for you.

library(patchwork)
library(tidyverse)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
p4 <- ggplot(mtcars) + geom_bar(aes(carb))

# side by side (ggplot)
p1 + p2

# side by side
p1 | p2

# vertical stacking
p1/p2/p3

# two by two
(p1|p2)/(p3|p4)

# two by one by one
(p1|p2)/(p3/p4)

# three by one
(p1 | p2 | p3) /  p4

# space between plots
p1 + plot_spacer() + p2 + plot_spacer() + p3 + plot_spacer()

# control number of columns
p1 + p2 + p3 + p4 + plot_layout(ncol = 3)

# control column widths
p1 + p2 + p3 + p4 + plot_layout(widths = c(2, 1))

# inset plot
p1 + inset_element(p2, left = 0.6, bottom = 0.6, right = 1, top = 1)

# Overall title
(p1 | (p2 / p3)) + plot_annotation(title = 'The surprising story about mtcars')

# tag plots
(p1 | (p2 / p3)) + plot_annotation(tag_levels = 'A')

# use gridExtra to add table
p1 | gridExtra::tableGrob(mtcars[1:10, c('mpg', 'disp')])