Ggplot2: print multiple graphs on one page using a loop

I have several themes for which I need to create a plot, since I have many objects that I would like to have several graphs on one page, and not one figure for the theme. Here is what I have done so far:

Read the txt file with the name of the objects

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

Create a list to store plot objects

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

}

At this point, I can display individual graphs, for example,

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

I like to have a solution, according to which several graphs are displayed on one page, I tried something in the lines of previous messages, but I can not get it to work.

eg:

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

gives me an error

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

I can use more basic graphic display functions, but I would like to achieve this using ggplot. Many thanks for the attention of Matilda.

+4
3

[[:

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"))))
+3
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)
+1

I'm sorry that I did not have a reputation for commenting instead of an answer, but you can use the following solution anyway to make it work.

I would do exactly what you did to get pltList, and then use the animation function from this recipe . Please note that you will need to specify the number of columns. For example, if you want to display all the graphs in a list in two columns, you can do this:

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

All Articles