ggplot2&facet_wrap - 消除小平面之间的垂直距离

pla*_*art 3 plot r ggplot2

我正在处理一些我希望显示为nxn网格图的数据.编辑:更清楚的是,我的数据中有21个类别.我希望按类别划分,并将这21个图形放在一个5 x 5平方网格中(其中孤儿本身位于第五行).因此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")
Run Code Online (Sandbox Code Playgroud)

这给了我几乎我想要的东西,但并不完全:

每个代码的虹膜数据集的图.

我在最上面一排的地块和底行之间仍然留有一小块空间.我想完全摆脱它,但panel.margin显然没有这样做.有没有办法做到这一点?

cr1*_*ade 7

panel.margin参数更改为panel.margin = unit(c(-0.5,0-0.5,0), "lines").出于某种原因,顶部和底部边距需要为负,才能完美排列.结果如下:

在此输入图像描述

  • 通过切换到 panel.margin.y = unit(c(-0.5,-0.5), "lines")、panel.margin.x = unit(0,"lines") 来修复它。我不知道 panel.margin 出了什么问题,但即使有点 hacky,它仍然有效。 (2认同)

hrb*_*str 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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


The*_*Guy 5

这可能有点晚,但panel.margin现在已弃用.内部theme使用panel.spacing.为了消除刻面之间的间距,然后加载grid包装并使用panel.spacing = unit(0, "lines")