title: R: saving ggplot2 plots in a list
body: <p>I am writing a R code that allows users to select columns from a data and plots histograms for each of them. Hence, I am using a 'for' loop to generate the required number of plots using the ggplot2 library and save them in a single list. But the problem I am facing is that, at every iteration of the 'for' loop, all objects in the list are storing the same plot. Thus, the final output consists of a grid of histograms, labeled differently but depicting the same(last) column. </p>
  
  <p>I understand that this question is quite old and I found the answers on <a href="https://stackoverflow.com/questions/6161371/renaming-ggplot2-graphs-in-a-for-loop">renaming ggplot2 graphs in a for loop</a> and <a href="https://stat.ethz.ch/pipermail/r-help/2008-February/154438.html" rel="nofollow noreferrer">https://stat.ethz.ch/pipermail/r-help/2008-February/154438.html</a> to be a useful starting point.</p>
  
  <p>I have used the standard Swiss Fertility dataset available in R to generate the plots. Here is the code:-</p>
  
  <pre><code>data_ &lt;- swiss
  data_ &lt;- na.omit(data_)
  
  u &lt;- c(2, 3, 4, 5, 6)
  plotData &lt;- data_[,u]
  bw &lt;- 5
  plotType &lt;- 'probability'
  
  library(ggplot2)
  library(gridExtra)
  
  histogramList &lt;- vector('list', length(u))
  
  if(plotType=='probability')
  {
   for(i in 1:length(u))
   {
     indexDataFrame &lt;- data.frame(plotData[,i])
     probabilityHistogram &lt;- ggplot(indexDataFrame, aes(x=indexDataFrame[,1]))
     histogramList[[i]] &lt;-  probabilityHistogram + geom_histogram(aes(y=..density..),     binwidth=bw, colour='black', fill='skyblue') + geom_density() + scale_x_continuous(names(plotData)[i]) + opts(legend.position='none')
   }
  } else
  if(plotType=='frequency')
  {
   for(i in 1:length(u))
   {
     indexDataFrame &lt;- data.frame(plotData[,i])
     probabilityHistogram &lt;- ggplot(indexDataFrame, aes(x=indexDataFrame[,1]))
     histogramList[[i]] &lt;- probabilityHistogram + geom_histogram(aes(y=..count..), binwidth=bw, colour='black', fill='skyblue') + geom_density() + scale_x_continuous(names(plotData)[i]) + opts(legend.position='none')
   }
  }
  
  arg_list &lt;- c(histogramList, list(nrow=3, ncol=2))
  #jpeg('histogram', width=1024, height=968)
  do.call(grid.arrange, arg_list)
  #graphics.off()
  </code></pre>
  
  <p>I apologize if I have missed an obvious answer to the question in this forum and shall be grateful if you could direct me towards it. I hope my explanation is clear and if not, please let me know about the clarifications required.</p>
  
  <p>Thanks! </p>