2016-04-27 20 views
0

我有一个DisplayPlot函数,它将一个字符串列表(它指的是数据框中的列)作为输入。 例如,如果list_string = c(“string1”,“string2”),循环list_string的元素,我想显示两个ggplots并排。R:并排显示功能内生成的可变数量的ggplots

到目前为止,我在我的功能所做的是存储ggplots成一个列表:

for (i in 1:length(list_string){ 
p = ggplot(data=d, aes(x=d[,1], y=as.numeric(levels(d[,(i+1)]))[d[,(i+1)]], fill=d[,1])) + 
    geom_bar(stat="identity") + 
    guides(fill=FALSE) + 
     labs(x = Y) + labs(y = paste("CP",list_X[i],"_per_",Y,sep = "")) 
graph[[length(graph) + 1]] <- p } 

,并返回:

return(list(graph=graph, along with some other information)) 

的问题是,如果我想使用的功能等grid.arrange,我需要手动写出图的名字:grid.arrange(p1,p2,ncol=2)而在我的情况下,这个数字可能会有所不同,并存储在一个列表中(grid.arrange不喜欢的格式)。

预先感谢您非常的帮助, 克莱门特

+5

作为一个侧面说明,你不应该使用'[ ''或'$'里面'aes' – baptiste

+0

为什么我不应该在aes里面使用它们? – galzra

+0

下面是一个可以出错的例子:http://stackoverflow.com/a/32543753/471093 – baptiste

回答

10
grid.arrange(grobs = graph) 

或(历史上,有没有总是grobs参数),

do.call(grid.arrange, graph) 
+0

谢谢,这工作很好。 multiplot()函数也是一个很好的解决方案 – galzra

-2

我找到了答案,以我的问题。

multiplot(plotlist=graph,col=length(list_string)) 

从Rmisc包

+1

这是比真实答案更多的评论.... – Jaap

+0

你应该说你从哪里得到了多功能函数。它似乎在一堆不同的包中,大部分来自[本指南的食谱](http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_%28ggplot2%29/) –