使用grid.arrange指定图表的宽度和高度

63
我有三个图表,想使用grid.arrange将它们合并。最后一个图表的高度应该比前两个小,并且所有图表的宽度应该相同。
以下是一个可用的示例:
p1 <- qplot(mpg, wt, data=mtcars)
p2 <- p1
p3 <- p1 + theme(axis.text.y=element_blank(), axis.title.y=element_blank())

grid.arrange(arrangeGrob(p1,p2, ncol=1, nrow=2),
         arrangeGrob(p3, ncol=1, nrow=1), heights=c(4,1)) 

enter image description here

在这里,最后一个图比前两个图宽。在我的真实数据中,即使我将文本和标题保留在y轴上,第三个图的宽度仍然不同。
我尝试添加“widths”:
 grid.arrange(arrangeGrob(p1,p2, ncol=1, nrow=2),
         arrangeGrob(p3, ncol=1, nrow=1), heights=c(4,1), widths=c(2,1))

但它变成了一个双列图...

enter image description here

我也尝试了另一段代码:

p1 <- ggplotGrob(p1)
p2 <- ggplotGrob(p2)
p3 <- ggplotGrob(p3)
# 
stripT <- subset(p2$layout, grepl("spacer", p2$layout$name))
p3 <- p3[-stripT$t, ]

grid.draw(rbind(p1, p2, p3, size = "first")) 

我有相同的宽度,但现在不知道如何改变高度...

enter image description here

好的,有人能帮我将高度和宽度结合起来制作最终的图表吗?

2个回答

65

尝试使用cowplot包中的plot_grid:

library(ggplot2)
library(gridExtra)
library(cowplot)
p1 <- qplot(mpg, wt, data=mtcars)
p2 <- p1
p3 <- p1 + theme(axis.text.y=element_blank(), axis.title.y=element_blank())
plot_grid(p1, p2, p3, align = "v", nrow = 3, rel_heights = c(1/4, 1/4, 1/2))

进入图片描述


当使用 plot_grid 时,如何将顶部和右侧轴带回来? - CrashOverride
theme_set(theme_grey()) - JAQuent
超棒。它可以与ggplot2一起使用! - Katelynn ruan

9
使用gtable时,您需要手动设置面板的高度。
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
g3 <- ggplotGrob(p3)

library(gridExtra)
g <- rbind(g1, g2, g3)

set_panel_heights <- function(g, heights){
  g$heights <- grid:::unit.list(g$heights) # hack until R 3.3 comes out
  id_panels <- unique(g$layout[g$layout$name=="panel", "t"])
  g$heights[id_panels] <- heights
  g
}

g <- set_panel_heights(g, lapply(1:3, grid::unit, "null"))
grid::grid.draw(g) 

在这里输入图片描述

虽然这种方法有点啰嗦,但比指定相对高度更通用:您可以混合各种网格单位。

grid::grid.newpage()
g <- do.call(rbind, replicate(3, ggplotGrob(ggplot()), simplify = FALSE))
g <- set_panel_heights(g, list(unit(1,"in"), unit(1,"line"), unit(1,"null")))
grid::grid.draw(g) 

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接