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

Mat*_*lde 5 loops r ggplot2 gridextra

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

读取带有主题名称的txt文件

subjs <- scan ("ListSubjs.txt", what = "")
Run Code Online (Sandbox Code Playgroud)

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

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)))

}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我可以显示单个图,例如

print (pltList[1]) #will print first plot
print(pltList[2]) # will print second plot
Run Code Online (Sandbox Code Playgroud)

我想有一个解决方案,通过它在同一页面中显示几个图,我已经尝试了以前帖子中的一些内容,但我没有设法让它工作

例如:

for (p in seq(length(pltList))) {
  do.call("grid.arrange", pltList[[p]])  
}
Run Code Online (Sandbox Code Playgroud)

给我以下错误

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

我可以使用更基本的绘图功能,但我想通过使用 ggplot 来实现这一点。非常感谢考虑 Matilde

bap*_*ste 5

您的错误来自使用以下索引对列表进行索引[[

考虑

pl = list(qplot(1,1), qplot(2,2))
Run Code Online (Sandbox Code Playgroud)

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

grid.arrange(grobs = pl)
Run Code Online (Sandbox Code Playgroud)

或者,等效地,

do.call(grid.arrange, pl)
Run Code Online (Sandbox Code Playgroud)

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

grid.arrange(grobs = pl[1:2])
do.call(grid.arrange, pl[1:2])
Run Code Online (Sandbox Code Playgroud)

可以使用第一种语法轻松传递更多参数;与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"))))
Run Code Online (Sandbox Code Playgroud)


Met*_*ics 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
Run Code Online (Sandbox Code Playgroud)

或者,

do.call(grid.arrange,pltList)
Run Code Online (Sandbox Code Playgroud)