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')
CodePudding user response:
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))
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))