ggplot2和gridExtra:完全删除facet_grid中的strip - 不仅仅是不可见的

Cla*_*ong 16 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)
Run Code Online (Sandbox Code Playgroud)

为此我需要顶部和底部图形的x轴排成一行,但是由于左边的条带,刻面图形比顶部图形窄.我可以使用以下方法使条带不可见:

theme(strip.text.y = element_blank())
theme(strip.background = element_blank())
Run Code Online (Sandbox Code Playgroud)

然而,这并没有摆脱条带所占据的空间.所以我要么需要一种方法来完全摆脱条带,或者有办法将我的分面图分割成单独的图形,但不知何故在它们之间共享相同的y轴标签.在我的图表中,我有两个不是很高的刻面板,并且没有足够的空间让每个都有一个像样的大小的y轴.

有什么建议?

Sim*_*lon 9

我的解决方案是找到条带的宽度,然后将两个图形的边距设置为零,但是将没有条带的边缘缩小到略小(条带的宽度),因此它们看起来大小相同.通过反复试验,似乎条带大约是0.5行宽(但我猜你可以用编程方式计算出来).因此,只需确保没有条带文本的图中的右边绘图边距比不可见条带大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)
Run Code Online (Sandbox Code Playgroud)

显然你可以根据需要调整边距(例如,在每个数字向量的第一个位置加1,以便在plot.margin每个图的顶部得到一条边的边框),只要在右边框中保留0.5行更多的边距即可第二个情节他们看起来一样.

在此输入图像描述