R Markdown

The goal of patchwork is to make it ridiculously simple to combine separate ggplots into the same graphic-

library(ggplot2)
library(patchwork)
theme_set(
  theme_bw() +
    theme(legend.position = "top")
  )

Add 2 graphs

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

p1 + p2

Add 4 graphs

p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
p4 <- ggplot(mtcars) + geom_bar(aes(carb))

(p1 | p2 | p3) /
      p4
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

# 0. Define custom color palette and prepare the data
my3cols <- c("#E7B800", "#2E9FDF", "#FC4E07")
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
# 1. Create a box plot (bp)
p <- ggplot(ToothGrowth, aes(x = dose, y = len))
bxp <- p + geom_boxplot(aes(color = dose)) +
  scale_color_manual(values = my3cols)

# 2. Create a dot plot (dp)
dp <- p + geom_dotplot(aes(color = dose, fill = dose), 
                       binaxis='y', stackdir='center') +
  scale_color_manual(values = my3cols) + 
  scale_fill_manual(values = my3cols)

# 3. Create a line plot
lp <- ggplot(economics, aes(x = date, y = psavert)) + 
  geom_line(color = "#E46726") 

# 4. Density plot
dens <- ggplot(iris, aes(Sepal.Length)) +
  geom_density(aes(color = Species)) +
  scale_color_manual(values = my3cols)

Horizontal layouts

bxp + dens

Customise layouts

(bxp | lp | dp) / dens
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

Customise layouts

(bxp + (dp + dens) + lp + plot_layout(ncol = 1)) & theme_gray()
## `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.

Reference:

  1. https://gotellilab.github.io/GotelliLabMeetingHacks/NickGotelli/ggplotPatchwork.html
  2. https://www.rdocumentation.org/packages/patchwork/versions/1.0.0
  3. https://www.littlemissdata.com/blog/patchwork
  4. https://www.datanovia.com/en/blog/ggplot-multiple-plots-made-ridiculuous-simple-using-patchwork-r-package/
  5. https://www.r4photobiology.info/2019/02/package-patchwork/
  6. https://cmdlinetips.com/2020/01/tips-to-combine-multiple-ggplots-using-patchwork/