Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 967
Esme_ Avatar asked Mar 26 '26 03:03

Esme_


1 Answers

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

like image 117
Ritchie Sacramento Avatar answered Mar 28 '26 17:03

Ritchie Sacramento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!