我有两张图,我将一张图放在另一张图上,如下所示:
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 以获得沿每个图顶部的一条线的边界),只要在第二个图的右边界它们看起来是一样的。关于r - ggplot2 和 gridExtra : completely remove strip in facet_grid - not just invisible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17144182/