r - ggplot2 和 gridExtra : completely remove strip in facet_grid - not just invisible

标签 r ggplot2 gridextra

我有两张图,我将一张图放在另一张图上,如下所示:

library(ggplot2)
library(gridExtra)
p1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p2 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p2 <- p2 + facet_grid(cyl ~ .)
grid.arrange(p1, p2, ncol=1)

为此,我需要顶部和底部图形的 x 轴对齐,但是由于左侧的 strip ,多面图形比顶部图形窄。我可以使用以下方法使 strip 不可见:
theme(strip.text.y = element_blank())
theme(strip.background = element_blank())

然而,这并没有消除 strip 占用的空间。所以我要么需要一种方法来完全摆脱 strip ,要么有一种方法将我的分面图拆分为单独的图,但不知何故在它们之间共享相同的 y 轴标签。在我的图表中,我有两个不太高的多面面板,并且没有足够的空间让它们每个都有一个合适大小的 y 轴。

有什么建议?

最佳答案

我的解决方案是找到 strip 的宽度,然后将两个图的边距设置为零,但将没有 strip 的那个缩小到稍微小一点( strip 的宽度),使它们看起来大小相同。通过反复试验,似乎 strip 宽约 0.5 行(但我想您可以通过编程方式计算出来)。因此,只需确保没有 strip 文本的图中的右图边距比带有不可见 strip 的图大 0.5 行:

#  Add a line of width 0.5 on the left but set all other margins to zero
p1 <- p1 + theme( plot.margin = unit( c(0,0.5,0,0) , units = "lines" ) )
#  Set all margins to zero, the strip will take up a phantom amount of invisible space
p2 <- p2 + theme(strip.text.y = element_blank() , 
  strip.background = element_blank(),
  plot.margin = unit( c(0,0,0,0) , units = "lines" ) )

grid.arrange(p1, p2, ncol=1)

显然,您可以根据需要调整边距(例如,在 plot.margin 中每个数字向量的第一个位置加 1 以获得沿每个图顶部的一条线的边界),只要在第二个图的右边界它们看起来是一样的。

enter image description here

关于r - ggplot2 和 gridExtra : completely remove strip in facet_grid - not just invisible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17144182/

相关文章:

r - 如何绘制交互项标准差变化的边际效应?

r - 将 grid.arrange 分配给对象

混合模型的残差建模: Any other package than nlme?

r - 如何在 R Shiny 和 plotly 中处理大量数据?

R- iGraph错误: weight vector too short,应用社区检测算法时值无效

r - 为什么 chisq.test 的 2 个输出在 R 中不同

r - 以编程方式检测 ggplot2 对象上 `theme()` 函数的属性是否已设置为 `element_blank()`

r - ggplot2 在具有多个分组的图例中正确显示分层点

r - 绘制 grobs 列表

r - 使用 marrangeGrob 每页的奇数图