使用列表将ggplot2图形按列而非行排列的网格排列方法

11

我希望使用grid.arrange从列表中创建ggplot2绘图的多面板显示,但要先按列排列,然后再按行排列。

gg_list1 <- list(qplot(mpg, disp, data = mtcars), 
                 qplot(hp, wt, data = mtcars), 
                 qplot(qsec, wt, data = mtcars))

gg_list2 <- list(qplot(mpg, disp, data = mtcars), 
                 qplot(hp, wt, data = mtcars), 
                 qplot(qsec, wt, data = mtcars))

我知道我能做到这件事:

do.call(grid.arrange,c(gg_list1,gg_list2 , ncol = 2, nrow  = 3))

但它会先从左到右填充,然后再从上到下。

我尝试过这样:

 do.call(grid.arrange, c(gg_list1, arrangeGrob(gg_list2, nrow = 3), ncol = 2))

但是出现错误:Error: length(widths) == ncol is not TRUE

有什么想法吗?

1个回答

17

您可以使用grobs参数传递一个列表,使用as.table参数以列方式填充,因此通过使用c展平所需的所有内容。

grid.arrange(grobs = c(gg_list1, gg_list2), ncol = 2, as.table = FALSE)

网格图

如果您想要更复杂的布局,请使用layout_matrix参数:

my_layout <- rbind(c(1, 1:3, 4), c(1, 1:3, 4), c(1, 1:3, 5), c(1, 1:3, 6))

my_layout
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    1    2    3    4
## [2,]    1    1    2    3    4
## [3,]    1    1    2    3    5
## [4,]    1    1    2    3    6

grid.arrange(grobs = c(gg_list1, gg_list2), layout_matrix = my_layout)

复杂的网格图

有关详细信息,请参见arrangeGrob文献


谢谢Alistaire。你的第一个例子使用grob =参数仍然是从左到右填充,然后再从上到下,顺便说一句,但是也许你已经知道了?你的第二个例子成功了!非常感谢 - 我已经在尝试解决这个问题了过去4小时,不是开玩笑的。 - Bonono
2
哎呀,你可以添加 as.table = FALSE 以按列填充;我会进行编辑。 - alistaire

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