Search code examples
rggplot2plotgraphicspatchwork

Annotate combined subplots (patchworks?) as single plots using patchwork


I'm trying to figure out how to annotate combined patchworks as if they were individual plots.

I've got one patchwork consisting of three combined plots and another single plot. The final composite plot is the first patchwork on top and the individual plot on the bottom. I have no problem getting the layout I want, but when I use plot_annotation, it gives letters to every plot, whereas what I'd like to see is an A for the top plot (patchwork of three subplots) and a B for the bottom one (just a single plot)

Here's what I'm currently doing:

library(ggplot2)
library(patchwork)

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')

top_plot = (p1 + p2 + p3)
bottom_plot = p4
combined_plot <- (top_plot / bottom_plot) + plot_annotation(tag_levels="A")
combined_plot

What I'd like to see, rather than A-D annotations, is A for the top plot (plots 1-3) and a B for the bottom one (plot 4). Is there a way to do this?


Solution

  • One solution is to create two complete patchwork plots, each with its own annotation. You have to put them each inside wrap_elements to declare them as complete patchworks for this to work. Thereafter you can combine them as you would combine ggplots:

    # Set theme for annotations
    thm <- theme(plot.title = element_text(face = 2, size = 16))
    
    top_plot      <- wrap_elements((p1 + p2 + p3) + 
                                     plot_annotation(title = "A", theme = thm))
    bottom_plot   <- wrap_elements(p4 + plot_annotation(title = "B", theme = thm))
    
    top_plot / bottom_plot
    

    enter image description here