2016-11-29 107 views
5

我想要使用grid.arrange從列表中創建ggplot2圖的多圖,但在按行排列之前按列排列圖。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

任何想法?

回答

6

可以使用grobs參數來傳遞一個列表和as.table參數,以填補逐列,因此與c夷爲平地,所有你需要的是

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

grid plot

如果你想要一個更復雜的佈局,使用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) 

complex grid plot

有關詳細信息,請參見the arrangeGrob vignette

+0

謝謝Alistaire。你的第一個使用'grob ='參數的例子在從上到下仍然是從左到右填充,fyi,但也許你知道嗎?你的第二個例子工作!非常感謝你 - 我一直試圖在過去的4小時里弄清楚這一點,不是開玩笑。 – Bonono

+2

糟糕。您可以添加'as.table = FALSE'來按列填充;我會編輯。 – alistaire