为了减少图形之间的空间,需要删除上面图形的底边距和下面图形的顶边距。以下代码将这些边距设置为0,这仍然会导致微小的白色空间在两个图形之间。您可以将这些边距稍微设置为负值(例如-0.1)以完全消除空间。我们使用gridExtra包中的grid.arrange函数而不是multiplot函数来布置这些图形。
library(grid)
library(gridExtra)
p1 = ggplot(mtcars, aes(wt, mpg)) + geom_point() +
xlab(NULL) +
theme(axis.text.x=element_blank(),axis.ticks.x=element_blank(),
plot.margin=unit(c(1,1,0,1), "lines"))
p2 = ggplot(mtcars, aes(wt, carb)) + geom_point() +
theme(plot.margin=unit(c(0,1,1,1), "lines"))
grid.arrange(p1, p2, ncol=1)
![图片描述](https://istack.dev59.com/4bidv.webp)
以上布局存在两个问题:(1) y轴未对齐,(2) 下图的绘图区高度小于上图。以下代码解决了这些问题:
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)
grid.arrange(gA, gB, heights=c(0.47,0.53), ncol=1)
![在此输入图片描述](https://istack.dev59.com/ox2KS.webp)
您可以使用与左对齐图形相同的技巧确切地使每个绘图区的高度相等(而不是使用grid.arrange
的heights
参数通过肉眼调整),但然后绘图边距会被添加回去。我不确定如何处理这个问题,但下面是参考代码:
maxHeight = grid::unit.pmax(gA$heights[2:5], gB$heights[2:5])
gA$heights[2:5] <- as.list(maxHeight)
gB$heights[2:5] <- as.list(maxHeight)