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

标签 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,非常感谢您的建议。

最佳答案

您传递给 do.call 的函数的参数真的应该是一个列表。来自 ?do.call :

args a list of arguments to the function call. The names attribute of args gives the argument names.



错误告诉您,您的其他参数正在传递给 grobs grid.arrange 的论据.为了阻止这种情况,把它放在一个列表中(c 在这里扁平化太多)并指定 grobs myplotslist 的参数名称:
do.call(grid.arrange, list(grobs = myplotslist, ncol=2, layout_matrix=cbind(c(1,2), c(3,4))))

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

关于r - 显示存储在列表中的一系列 ggplot 图时控制布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802295/

相关文章:

R - 如何在 PDF 的一页上打印三个以上的表格

r - 时间序列及其可视化

r - 在 ggplot2 中绘制 envfit 向量(vegan 包)

通过导航到 navbarPage 中的特定 tabPanel 触发 R Shiny 响应式(Reactive)

R函数,nnet : what exactly "weights" input does?

r - 使用多个标签手动注释一个面板

r - 在多个页面上绘图

r - 结合 barplot 和 grid.table

r - ggplot 在同一面板中组合线和区域(facet-grid)

r - 列表中的 bind_rows 即使 class() 不同