显示存储在列表中的一系列ggplot图时控制布局

时间:2016-01-15 00:22:38

标签: r ggplot2 gridextra

我想在绘制一系列ggplots时控制布局 我已经存储在列表中(在其他地方自动生成)。

我可以如下绘制一系列情节。

library(ggplot2)
library(grid)
library(gridExtra)
p1 <- ggplot(mtcars, (aes(x=mpg, fill=as.factor(1)))) + geom_density() +  
                      scale_fill_manual(values="red") 
p2 <- ggplot(mtcars, (aes(x=mpg, fill=as.factor(1)))) + geom_density() +  
                      scale_fill_manual(values="orange") 
p3 <- ggplot(mtcars, (aes(x=mpg, fill=as.factor(1)))) + geom_density() +  
                      scale_fill_manual(values="yellow") 
p4 <- ggplot(mtcars, (aes(x=mpg, fill=as.factor(1)))) + geom_density() +  
                      scale_fill_manual(values="green") 
grid.arrange(p1, p2, p3, p4)

grid.arrange basic

然后我可以更改其布局,如here所示。

grid.arrange(p1, p2, p3, p4, layout_matrix=cbind(c(1,2), c(3,4)))

grid.arrange new layout

我还可以绘制一系列图表,如果它们存储在列表中,如here所示。

myplotslist <- list(p1, p2, p3, p4)
do.call(grid.arrange, c(myplotslist, ncol=2))

enter image description here

但如果我尝试使用layout_matrix更改布局,则会收到错误(以及一些警告)。

do.call(grid.arrange, c(myplotslist, ncol=2, layout_matrix=cbind(c(1,2), c(3,4))))

Error in gList(list(grobs = list(list(x = 0.5, y = 0.5, width = 1, height = 1,  : 
  only 'grobs' allowed in "gList"
In addition: Warning messages:
1: In grob$wrapvp <- vp : Coercing LHS to a list
2: In grob$wrapvp <- vp : Coercing LHS to a list
3: In grob$wrapvp <- vp : Coercing LHS to a list
4: In grob$wrapvp <- vp : Coercing LHS to a list

我曾尝试将绘图对象强制转换为grob,但遇到同样的错误。

myplotslist2 <- list(ggplotGrob(p1), ggplotGrob(p2), ggplotGrob(p3), ggplotGrob(p4))

我使用的是R 3.2.1,ggplot2 2.0.0,grid 3.2.1和gridExtra 2.0.0,非常感谢您的建议。

2 个答案:

答案 0 :(得分:4)

传递给do.call的函数的参数实际上应该是一个列表。来自?do.call

  

args 列表函数调用的参数。 names的{​​{1}}属性   args给出参数名称。

错误告诉您,您的其他参数已传递给grobs的{​​{1}}参数。要停止它,请将其放在一个列表中(grid.arrange在这里展平太多)并为c指定grobs参数名称:

myplotslist

...或者你可以完全抛弃do.call(grid.arrange, list(grobs = myplotslist, ncol=2, layout_matrix=cbind(c(1,2), c(3,4)))) (h / t Baptiste):

do.call

答案 1 :(得分:2)

不太确定原因,但这似乎有效:

do.call(grid.arrange, c(myplotslist, ncol=2, layout_matrix=list(cbind(c(1,2), c(3,4)))))