如何在grid.newpage()中grid.arrange()

时间:2014-08-02 06:30:13

标签: r ggplot2 gridextra

我有以下网格图

library(ggplot2)
library(gridExtra)

df1 <- data.frame(Var1 = rnorm(100), Var2 = rnorm(100) )
df2 <- data.frame(Var1 = rnorm(100), Var2 = rnorm(100, sd = 1000000) )

wide1 <- ggplot(df1, aes(x=Var1, y=Var2)) + geom_point()
wide2 <- ggplot(df2, aes(x=Var1, y=Var2)) + geom_point()
wide3 <- ggplot(df1, aes(x=Var1, y=Var2)) + geom_point()
narrow1 <- ggplot(df1, aes(x=Var1, y=Var2)) + geom_point()

grid.newpage() # Open a new page on grid device
pushViewport(viewport(layout = grid.layout(5, 3)))
print(wide1, vp = viewport(layout.pos.row = 3, layout.pos.col = 1:3))
print(wide2, vp = viewport(layout.pos.row = 4, layout.pos.col = 1:3))
print(wide1, vp = viewport(layout.pos.row = 5, layout.pos.col = 1:3))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 1)) 
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 2))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 3))

正确绘制

enter image description here

然而,由于Y轴标签,底部的第二个图被压缩,并且未与其他两个宽图对齐。通常我会按照以下步骤确保三个宽图对齐

gp1<- ggplot_gtable(ggplot_build(wide1))
gp2<- ggplot_gtable(ggplot_build(wide2))
gp3<- ggplot_gtable(ggplot_build(wide3))
maxWidth = unit.pmax(gp1$widths[2:3], gp2$widths[2:3],gp3$widths[2:3])
gp1$widths[2:3] <- maxWidth
gp2$widths[2:3] <- maxWidth
gp3$widths[2:3] <- maxWidth
grid.arrange(gp1,gp2,gp3)

产生

enter image description here

然而,当我在grid.arrange()内尝试grid.newpage()时,它并没有产生我所希望的......

grid.newpage() # Open a new page on grid device
pushViewport(viewport(layout = grid.layout(5, 3)))
print(grid.arrange(gp1,gp2,gp3), vp = viewport(layout.pos.row = 3:5, layout.pos.col = 1:3))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 1)) 
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 2))
print(narrow1, vp = viewport(layout.pos.row = 1:2, layout.pos.col = 3))

1 个答案:

答案 0 :(得分:3)

print(arrangeGrob(gp1,gp2,gp3), vp=..., newpage=FALSE)