How can I add a second title in ggplot2 using patchwork?

Viewed 283

Suppose I want to merge the following six plots into one plot.

library(ggplot2)
p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp))

p2 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp))

p3 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp)) 

p4 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp))

p4 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp))

p5 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp))

p6 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp))

For this I use the package Pachwork:

 library(patchwork)
    
    (p1 | p2  | p2 ) / (p4  | p5  | p6 ) + 
      plot_annotation(title = "Perceptual Domain", tag_levels = 'A') & 
      theme(plot.title = element_text(hjust = 0.5), plot.tag = element_text(size = 15, face = "bold")) 

I want to add a title for the upper three plots and a separate title for the lower three plots.

As you can see in the example I can only add one title but not a second one.

Can someone help me and show me how I can add a second title for the lower three plots?

1 Answers

One option to achieve your desired result would be to make separate patchworks for the top and the bottom level plots and glue them together by wrapping them inside patchwork::wrap_elements. Note that this approach requires some "manual" work to set the tag levels for the bottom level plot:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp))

p11 <- (p1 | p1  | p1 ) +
  plot_annotation(title = "Title 1", tag_levels = "A") & 
  theme(plot.title = element_text(hjust = 0.5), plot.tag = element_text(size = 15, face = "bold"))

p12 <- (p1 | p1  | p1 ) +
  plot_annotation(title = "Title 2", tag_levels = list(c("D", "E", "F"))) & 
  theme(plot.title = element_text(hjust = 0.5), plot.tag = element_text(size = 15, face = "bold"))

wrap_elements(p11) / wrap_elements(p12)

Related