将多个图例与拼凑对齐

Align multiple legends with patchwork

this vignette of patchwork 中解释了如何组合多个 ggplot。我遇到的一个困难是当它们的标题在字符数上相差很大时,如何正确地收集图例和 align/justify 它们。

下面是一个示例 - 我希望 'mpg' 图例也左对齐/对齐,而不是在 'Size' 图例下方居中。有什么建议么?请注意,添加 theme(legend.justification = "left") 并不能解决问题。

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp, colour = mpg, size = wt)) + 
  guides(size = guide_legend(title = "Size - long title for the purpose of this example")) +
  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')

(p1 | (p2 / p3)) + plot_layout(guides = 'collect')

reprex package (v0.3.0)

创建于 2019-12-16

同时,this was fixed by Ilia Kats.

现在可以使用 & theme(legend.justification = "left")(将图例 separate/aligned 保留在情节中)或 + plot_layout(guides = 'collect')(合并情节中的图例)。

使用 remotes::install_github("thomasp85/patchwork") 更新 patchwork(如果早于 ~2020)。


详细示例:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) +
  geom_point(aes(mpg, disp, colour = mpg, size = wt)) +
  guides(size = guide_legend(title = "Size - long title for the purpose of this example")) +
  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')

OP 的大小写已修复:

(p1 | (p2 / p3)) + plot_layout(guides = 'collect')

但是默认大小写还是没有对齐:

(p1 / p3)

通过合并参考线对齐(现已修复):

(p1 / p3) + plot_layout(guides = 'collect')

左对齐(现已修复):

(p1 / p3) & theme(legend.justification = "left")

(如果两个图之间没有共享图例,这将是可取的(所以这只是一个不好的使用示例))

reprex package (v0.3.0)

于 2020-09-10 创建
# Session info: 
R version 4.0.1 (2020-06-06),            
 ggplot2     * 3.3.1      2020-05-28 [1] CRAN (R 4.0.0)                        
 patchwork   * 1.0.1.9000 2020-09-10 [1] Github (thomasp85/patchwork@82a5e03)