要减少图之间的空间,请删除顶部图的底部边距并删除底部图的顶部边距。下面的代码将这些边距设置为 0,这仍然会导致图之间有一点空白。您可以使这些边距略微为负(可能是 -0.1 左右)以完全删除空白。我们使用 gridExtra 包中的 grid.arrange 而不是 multiplot 函数来布置绘图。 :
library(grid)
library(gridExtra)
## Create two sample plots with the same x axis using built-in mtcars data frame
# Top plot: Remove bottom margin, x-labels, and x title
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"))
# Bottom plot: Remove top margin
p2 = ggplot(mtcars, aes(wt, carb)) + geom_point() +
theme(plot.margin=unit(c(0,1,1,1), "lines"))
# Lay out plots in one column
grid.arrange(p1, p2, ncol=1)
上述布局有两个问题:(1) y 轴没有正确对齐,(2) 下图的绘图区域的高度小于上图的绘图区域的高度。下面的代码解决了这些问题:
# Left justify plots
# Source: http://stackoverflow.com/a/13295880/496488
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)
# Lay out justified plots. Use heights argument to equalize heights of each plot area
grid.arrange(gA, gB, heights=c(0.47,0.53), ncol=1)
您可以使用与左对齐绘图相同的技巧(而不是使用 heights 到 grid.arrange 的参数通过肉眼进行操作)精确地平衡每个绘图区域的高度,然后绘图边距加回来。我不确定如何处理,但这里有代码供参考:
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)