Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R ggplot2 patchwork place legend on the top right hand corner

By default the legend is placed at the center of the white empty space towards the right.

Based on the data and code below, how can I place the legend on the upper right hand corner of the empty space?

Sample data and code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(patchwork)    
library(tidyverse)

gg1 = ggplot(mtcars) + 
  geom_point(aes(mpg, disp, color = mpg)) + 
  ggtitle('Plot 1')

gg2 = ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  ggtitle('Plot 2')

gg3 = ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')
     
gg1 + gg2 + gg3  + plot_layout(guides = 'collect') 

>Solution :

The simplest way is probably just to add a margin to the legend.

gg1 + gg2 + gg3  + 
  plot_layout(guides = 'collect') & 
  theme(legend.margin = margin(0, 0, 200, 0))

enter image description here

Or change its vertical justification to 1 (which will keep the position stable as the device size is rescaled)

gg1 + gg2 + gg3  + 
  plot_layout(guides = 'collect') & 
  theme(legend.justification = c(0.5, 1))

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading