ggplot传说可以在情节之外自由移动吗?

时间:2018-05-09 11:18:21

标签: r ggplot2 cowplot

我有这个问题,用cowplot ::: plot_grid绘制的情节只需几毫米即可切割左侧情节的图例。图例大小已经处于可读性的绝对最小值,两个图之间的空白区域是可以的(所以它不是我想要操纵的边距)。但是,即使有理由="左",图例也比绘图面板大一点,然后在

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

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

enter image description here

左侧仍有足够的空白区域。我知道传说可以在情节内自由移动,但是如果它在绘图之外绘制,是否可以将距离其理由锚点几厘米的传说移动?

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

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)

目前,我的解决方法是打印单个图并使用插图画家进行操作,这样就可以避免使用。

2 个答案:

答案 0 :(得分:4)

你可以尝试

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

enter image description here

答案 1 :(得分:1)

这可能看起来像一个牛皮画错误但它不是,并且它不会发生在牛皮画主题上。问题在于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))

enter image description here

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