Search code examples
rggplot2patchwork

Manually position legend in Patchwork


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

Solution

  • 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