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

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

3个回答

5
你的错误来自使用[[索引列表:
请考虑
pl = list(qplot(1,1), qplot(2,2))

pl[[1]] 返回第一个图,但是 do.call 期望一个参数列表。你可以使用 do.call(grid.arrange, pl)(没有错误)来实现,但这可能不是你想要的(它会在页面上排列一个图表,这样做没有什么意义)。假设你想要所有的图表,

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

请为此添加必要的导入(在阅读下一个答案之前,我无法猜测import(gridExtra))。 - Joseph Budin

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)

感谢您的帮助,但是似乎这不起作用。在arrangeGrob(...,as.table = as.table,clip = clip,main = main,:输入必须是grobs! - Matilde
我想这可能与你的布局有关。看看这个网址:http://stackoverflow.com/questions/21343372/arrangegrob-error-when-using-ggplot2-in-a-function - Metrics

0
我希望我有足够的声望来发表评论而不是回答,但是无论如何,您可以使用以下解决方案使其工作。
我将完全重复您获取pltList的操作,然后使用this recipe中的multiplot函数。请注意,您需要指定列数。例如,如果您想要在两列中绘制列表中的所有图形,则可以执行以下操作:
print(multiplot(plotlist=pltList, cols=2))

这里的 multiplot 函数是什么?我似乎找不到它。 - Joseph Budin
这里定义了它(http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_%28ggplot2%29/)。 - crwang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接