ggplot2和facet_wrap - 消除分面之间的垂直距离

6
我正在处理一些数据,想要将其显示为一个nxn的图形网格。 编辑: 为了更加清晰,我的数据中有21个类别。我想按照类别进行分面,并在一个5 x 5的正方形网格中显示这21个图形(其中孤立的图形位于第五行)。因此使用facet_wrap而不是facet_grid。
我已经编写了以下代码来实现它(使用经典的鸢尾花数据集作为可重现的示例):
library(ggplot2)
library(grid)

cust_theme <- theme_bw() + theme(legend.position="none", 
              axis.title = element_blank(), axis.ticks = element_blank(), 
              axis.text = element_blank(), strip.text = element_blank(), 
              strip.background = element_blank(), panel.margin = unit(0, "lines"), 
              panel.border = element_rect(size = 0.25, color = "black"), 
              panel.grid = element_blank())

iris.plot <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
             geom_point() + cust_theme + facet_wrap( ~ Species, ncol = 2) + 
             labs(title = "Irises by species")

这几乎实现了我想要的,但还差一点:

iris数据集的图表(根据上面的代码)

我仍然在顶行图形和底部行之间有一小条空白。我希望完全消除它,但panel.margin显然做不到。有没有办法做到这一点?


你可能希望将+运算符放在行的末尾,因为现有的代码会在R脚本中产生错误。或者,你可以将整个绘图调用用括号括起来。 - cr1msonB1ade
@cr1msonB1ade 谢谢,说得好。我的代码本来是一行的,但为了可读性我把它分成了几行。已经修复了。 - plagueheart
3个回答

10

也许有点晚了,但是panel.margin现在已被弃用。在theme中使用panel.spacing代替。如果想要消除分面间的间距,则加载grid包并使用panel.spacing = unit(0, "lines")


panel.spacing 管理面板之间的间隙。但是我们如何管理线图和边框之间的间隙呢?是否有一种类似的方法来填充 y 轴和 x 轴的极端端点之间的像素? - Lazarus Thurston
你是指 plot.margin 吗?如果你只是想扩大图表的大小(靠近边缘),你可以使用类似 theme(plot.margin = unit(c(0.5,0.2,0.5,1), "cm")) 的东西。只需要找到最适合你的尺寸即可。 - TheSciGuy
谢谢。当我回到我的旧图时,标签文本(在线上方)被裁剪在边界处时,我会记住这个问题的。 - Lazarus Thurston

8
panel.margin参数更改为panel.margin = unit(c(-0.5,0-0.5,0), "lines")。由于某种原因,顶部和底部的边距需要是负数才能完美对齐。以下是结果:

enter image description here


哦,太好了!我猜你需要强制让它们变成负数,因为即使没有绘制,那个空间也是保留给x轴的。 - plagueheart
不错的技巧。@plagueheart,这个空间实际上是为面条带保留的。 - Jaap
@Jaap 哦,明白了。谢谢你的帮助! - plagueheart
1
好吧,这很令人沮丧——由于某种原因,它在我的虚拟图中正常工作,但是当我将其应用于我之前处理的原始情况时,间隙仍然存在。 - plagueheart
2
通过切换到panel.margin.y = unit(c(-0.5,-0.5), "lines"), panel.margin.x = unit(0,"lines")来解决了问题。我不知道仅使用panel.margin出了什么问题,但这个方法虽然有点hacky,但是可以工作。 - plagueheart

5

您也可以直接编辑grobs:

library(ggplot2)
library(grid)

g <-  ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  facet_wrap( ~ Species, ncol = 2) +
  labs(title = "Irises by species") +
  theme_bw() +
  theme(panel.margin = unit(0, "lines")) +
  theme(plot.margin = unit(c(0,0,0,0), "lines")) +
  theme(strip.background = element_blank()) +
  theme(plot.background = element_blank()) +
  theme(strip.text = element_blank()) +
  theme(axis.ticks.margin = unit(0, "lines"))

g <- ggplotGrob(p)

g$heights[[7]] = unit(0, "lines")

grid.newpage()
grid.draw(g)

enter image description here


非常好,谢谢。我对于使用grobs还有点害羞,但我最终会掌握的——将这个作为另一种解决方案记在心里。 - plagueheart

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