9

I want to position a legend (common to all plots) in a blank space in a patchwork layout. From what I can find online I cannot manually position a legend using legend.position if I also use guides="collect" (but can use left, right etc.).

I have tried to use l <- get.legend and then + inset_element(l, 0.6, 0.6, 1, 1) however it doesn't understand l. I also tried mixing in + inset_element(gridExtra::tableGrob(l)) without luck.

My goal is to place the legend in the blank space. My actual patchwork plot is more complicated but has two blank spaces I want the legend to sit in.

MWE

library(patchwork)    
library(ggplot2)
p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp, color = mpg)) + 
  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')    

design <- "
1111
223#
"    
p1 + p2 + p3  + plot_layout(guides = 'collect') + plot_layout(design=design, guides = "collect")  &
  theme(legend.position = 'right',
        legend.direction = 'vertical')
Esme_
  • 1,360
  • 3
  • 18
  • 30

1 Answers1

15

Alter your design object to include a fourth element and use guide_area() to place the guide.

library(patchwork)    
library(ggplot2)

design <- "
1111
2234
"    
p1 + p2 + p3 + guide_area() + plot_layout(design=design, guides = "collect") 

enter image description here

Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
  • 1
    is there a way to position the legend within the guide_area()? For example, could you push it all the way to the right in this example? – rrr Dec 23 '22 at 03:13
  • Good question. I don't know of a way to do this via the current API. I imagine it could be done by manipulating the grob or perhaps a simpler workaround would be to play with the design element ratios to insert empty space to the left of the guide. If you want a proper answer it would be best to post a new question. – Ritchie Sacramento Dec 30 '22 at 08:41