Ed_Gravy
Ed_Gravy

Reputation: 2033

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:

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

Upvotes: 1

Views: 419

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

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

Upvotes: 2

Related Questions