对齐分面图和图例

4

我正在尝试绘制多面板图,每个面板都有自己的图例。然而,我遇到了一些问题,无法将它们正确地对齐。

dat <- structure(list(group1 = structure(c(1L, 1L, 2L, 2L, 2L), .Label = c("A", 
"B"), class = "factor"), group2 = structure(c(1L, 2L, 1L, 3L, 
2L), .Label = c("a", "b", "c"), class = "factor"), x = c("1", 
"2", "3", "4", "2"), y = c("1", "2", "3", "4", "3")), .Names = c("group1", 
"group2", "x", "y"), row.names = c(NA, 5L), class = "data.frame")

dat <- split(dat, f = dat$group1)

library(ggplot2)
p1 <- ggplot(dat$A) +
  geom_point(aes(x=x, y=y, colour=group2)) +
  facet_wrap(~group1) +
  guides(colour=guide_legend(nrow=2)) +
  scale_colour_manual(values=c(a = "green", b = "red", c = "blue"), 
                      labels=c(a = "green", b = "red", c = "blue"))

p2 <- p1 %+% dat$B

使用gridExtra的问题是图形不对齐:
library(gridExtra)
grid.arrange(p1, p2, p2, p1, ncol=2)

enter image description here

使用cowplot后,图例有些居中:

library(cowplot)
plot_grid(p1, p2, p2, p1, ncol=2, align="hv")

我尝试添加 legend.justification 和/或 legend.position,但没有效果。

enter image description here

如何使绘图和图例都对齐?

我们可以添加 guides(col = guide_legend(nrow = 3)),以便图例占用相同的宽度大小。 - zx8754
@zx8754我的真实数据有许多更多的因子水平,根据分面可达到2-10个不等。无法避免地需要多列但列数会变化。 - erc
1个回答

8
您可以尝试 实验性的egg
grid.draw(ggarrange(plots=list(p1,p2,p2,p1)))

请注意,ggplot2每次更新都有破坏此类代码的习惯,因此请将其视为易碎的解决方法。

enter image description here


谢谢,我需要做什么才能访问ggarrange函数呢? - erc
2
@beetroot: 使用devtools::install_github('baptiste/egg')来安装它。 - Cath
谢谢你的帮助,现在对于我的示例来说它可以工作了。但是对于我的实际数据,我得到了错误:Error: ncol(x) == ncol(y) is not TRUE - erc
@beetroot 你能分享一个最简单的例子吗? - baptiste
当然,看起来问题是图形数量不均匀? grid.draw(ggarrange(plots=list(p1,p2,p2,p1,p2))) - erc
2
现在完美地运行了。非常感谢您的帮助,也感谢您在gridExtra等方面的出色工作。 :) - erc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接