5

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

读取带有主题名称的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 来实现这一点。非常感谢考虑 Matilde

4

3 回答 3

5

您的错误来自索引列表[[

考虑

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"))))
于 2015-07-25T21:59:23.133 回答
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

或者,

do.call(grid.arrange,pltList)
于 2015-02-16T20:09:21.573 回答
0

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

我会按照你所做的那样来获取 pltList,然后使用这个配方中的 multiplot 函数。请注意,您需要指定列数。例如,如果要将列表中的所有图绘制成两列,可以这样做:

print(multiplot(plotlist=pltList, cols=2))
于 2015-07-25T02:14:24.010 回答