我想在一个拼贴布局的空白区域中放置一个图例 (适用于所有子图)。根据我在网上找到的资料,如果我使用 guides="collect"
(但可以使用 left、right 等),就不能使用 legend.position
手动定位图例。
我尝试过使用 l <- get.legend
,然后再使用 + inset_element(l, 0.6, 0.6, 1, 1)
,但它无法识别 l
。我还尝试了混入 + inset_element(gridExtra::tableGrob(l))
,但没有成功。
我的目标是将图例放置在空白区域中。我的实际拼贴图更复杂,但有两个空白区域我希望图例放在其中。
最小工作示例:
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')