在 Patchwork 中手动定位图例

Manually position legend in Patchwork

我想在拼图布局的空白 space 中放置一个图例(所有地块通用)。根据我在网上可以找到的内容,如果我也使用 guides="collect"(但可以使用左、右等),我无法使用 legend.position 手动定位图例。

我试过使用 l <- get.legend 然后 + inset_element(l, 0.6, 0.6, 1, 1) 但是它不理解 l。我也试过混入 + inset_element(gridExtra::tableGrob(l)) 但运气不好。

我的目标是将图例放在空白处 space。我的实际拼凑图更复杂,但有两个空白 space 我希望图例位于其中。

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

更改您的 design 对象以包含第四个元素并使用 guide_area() 放置指南。

library(patchwork)    
library(ggplot2)

design <- "
1111
2234
"    
p1 + p2 + p3 + guide_area() + plot_layout(design=design, guides = "collect")