ggplot2:使用循环在一个页面中打印多个图

时间:2015-02-16 19:38:05

标签: r loops ggplot2 gridextra

我有几个主题,我需要生成一个情节,因为我有很多主题,我想在一个页面中有几个图而不是一个主题图。 这是我到目前为止所做的:

阅读主题名称为

的txt文件
subjs <- scan ("ListSubjs.txt", what = "")

创建一个列表来保存绘图对象

pltList <- list()

for(s in 1:length(subjs))
{ 

  setwd(file.path("C:/Users/", subjs[[s]])) #load subj directory
  ifile=paste("Co","data.txt",sep="",collapse=NULL) #Read subj file
  dat = read.table(ifile)
  dat <- unlist(dat, use.names = FALSE) #make dat usable for ggplot2
  df <- data.frame(dat)

  pltList[[s]]<- print(ggplot( df, aes(x=dat)) +  #save each plot with unique name  
    geom_histogram(binwidth=.01, colour="cyan", fill="cyan") +
    geom_vline(aes(xintercept=0),   # Ignore NA values for mean
               color="red", linetype="dashed", size=1)+
   xlab(paste("Co_data", subjs[[s]] , sep=" ",collapse=NULL)))

}

此时我可以显示单个图,例如

print (pltList[1]) #will print first plot
print(pltList[2]) # will print second plot

我希望有一个解决方案,在同一页面中显示几个图表,我尝试了以前的帖子,但我没有设法让它工作

例如:

for (p in seq(length(pltList))) {
  do.call("grid.arrange", pltList[[p]])  
}

给我以下错误

Error in arrangeGrob(..., as.table = as.table, clip = clip, main = main, : input must be grobs!

我可以使用更基本的图形功能,但我想通过使用ggplot来实现这一点。非常感谢您的考虑 马蒂尔德

3 个答案:

答案 0 :(得分:4)

您的错误来自使用[[索引列表:

考虑

pl = list(qplot(1,1), qplot(2,2))

pl[[1]]返回第一个图,但do.call需要列表参数。您可以使用do.call(grid.arrange, pl[1])(没有错误),但这可能不是您想要的(它在页面上排列一个情节,这样做没什么意义)。大概你想要所有的情节,

grid.arrange(grobs = pl)

或等同地

do.call(grid.arrange, pl)

如果您想要选择此列表,请使用[

grid.arrange(grobs = pl[1:2])
do.call(grid.arrange, pl[1:2])

可以使用第一种语法简单地传递其他参数;必须注意do.call以确保列表的格式正确,

grid.arrange(grobs = pl[1:2], ncol=3, top=textGrob("title"))
do.call(grid.arrange, c(pl[1:2], list(ncol=3, top=textGrob("title"))))

答案 1 :(得分:1)

library(gridExtra) # for grid.arrange
library(grid) 
grid.arrange(pltList[[1]], pltList[[2]], pltList[[3]], pltList[[4]], ncol = 2, main = "Whatever") # say you have 4 plots

OR,

do.call(grid.arrange,pltList)

答案 2 :(得分:0)

我希望我有足够的声誉来评论而不是回答,但无论如何,您可以使用以下解决方案来使其发挥作用。

我会完全按照你所做的去获取pltList,然后使用this recipe中的多重时隙函数。请注意,您需要指定列数。例如,如果要将列表中的所有绘图绘制为两列,则可以执行以下操作:

print(multiplot(plotlist=pltList, cols=2))