ggplot图例可以在情节外自由移动吗?

Can ggplot legends be moved freely outside the plot?

我有这个问题,用 cowplot:::plot_grid 绘制的图只将左侧图的图例削减了几毫米。图例大小已经处于可读性的绝对最小值,并且两个图之间的白色 space 没问题(所以它不是我想要操纵的边距)。然而,即使有 justification="left",图例也比绘图面板大一点,然后在

之后被剪切
plot_grid(px, p2, align="h", nrow=1, rel_widths = c(1,0.675))

ggsave("plot.tiff", width=8.27, height=11.69/4)

左边还有足够的白色space。我知道图例可以在图内自由移动,但是如果图例绘制在图外,是否可以将图例移动到距其对齐锚点仅几厘米的位置?

这个例子确实重现了这个问题,并且包含了我现实生活中的例子特征的许多论点(例如,以两种不同的宽度绘制网格),但我不得不放大图例的字体大小,这个例子确实如此图例左侧没有额外的白色 space。

bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) +
  geom_boxplot() + theme_bw() +
  theme(legend.text = element_text(size=20), # IRL the font size is much smaller
        axis.text.y=element_blank(),
        legend.key.size = unit(0.2, "cm"),
        legend.position = "bottom",
        legend.justification="left")+
  guides(fill=guide_legend(nrow=3)) +
  coord_flip() 
bp
bp1 <- bp + scale_fill_discrete("",labels=c("reallyreallyreallylongstring", 
                                         "evenlongerstring", 
                                         "youcannotbelievehowlongthisstringis!!11!"))


library(cowplot)
plot_grid(bp1, bp, align="h", nrow=1, rel_widths = c(1,0.675))
ggsave("test.tiff", width=8.27, height=11.69/4)

目前,我的解决方法是打印单个图并使用 illustrator 对其进行操作,这是我想避免的。

你可以试试

# get legend
legend_p1 <- get_legend(bp1)
legend_p2 <- get_legend(bp)

# remove legend
bp1_wl <- bp1 + theme(legend.position='none')
bp_wl <- bp + theme(legend.position='none')

# plot
plot_grid(plot_grid(bp1_wl, bp_wl, align="h", rel_widths = c(1,0.675)),
          plot_grid(legend_p1,legend_p2, rel_widths = c(1,0.675)), nrow=2, rel_heights = c(1,0.4))

这可能看起来像一个 cowplot 错误,但它不是,而且它不会发生在 cowplot 主题上。问题在于 theme_bw():第二个图的背景是白色,绘制在第一个图的顶部。如果删除白色背景,图例可以从一个图重叠到另一个图。

library(ggplot2)
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) +
  geom_boxplot() + theme_bw() +
  theme(legend.text = element_text(size=20), # IRL the font size is much smaller
        axis.text.y=element_blank(),
        legend.key.size = unit(0.2, "cm"),
        legend.position = "bottom",
        legend.justification="left",
        # here we're removing plot background, legend background,
        # and legend box background, to be sure
        plot.background = element_blank(),
        legend.background = element_blank(),
        legend.box.background = element_blank())+
  guides(fill=guide_legend(nrow=3)) +
  coord_flip() 
bp
bp1 <- bp + scale_fill_discrete("",labels=c("reallyreallyreallylongstring", 
                                            "evenlongerstring", 
                                            "youcannotbelievehowlongthisstringis!!11!"))


library(cowplot)
plot_grid(bp1, bp, align="h", nrow=1, rel_widths = c(1,0.675))

(我目前是 运行 ggplot2 的开发版本,我必须看看为什么图例在图的左侧用完了,但这是一个单独的问题。)