title: Save plots as R objects and displaying in grid
body: <p>In the following reproducible example I try to create a function for a ggplot distribution plot and saving it as an R object, with the intention of displaying two plots in a grid.</p>
  
  <pre><code>ggplothist&lt;- function(dat,var1)
  {
          if (is.character(var1)) {
              var1 &lt;- which(names(dat) == var1) 
      }
      distribution &lt;- ggplot(data=dat, aes(dat[,var1])) 
      distribution &lt;- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
      output&lt;-list(distribution,var1,dat)
      return(output)
  }
  </code></pre>
  
  <p>Call to function:</p>
  
  <pre><code>set.seed(100)
  df  &lt;- data.frame(x = rnorm(100, mean=10),y =rep(1,100))    
  output1 &lt;- ggplothist(dat=df,var1='x')
  output1[1]
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/8N1Mt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8N1Mt.png" alt="enter image description here"></a></p>
  
  <p>All fine untill now.</p>
  
  <p>Then i want to make a second plot, (of note mean=100 instead of previous 10)</p>
  
  <pre><code>df2  &lt;- data.frame(x = rep(1,1000),y = rnorm(1000, mean=100))    
  output2 &lt;- ggplothist(dat=df2,var1='y')
  output2[1]
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/gijZu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gijZu.png" alt="enter image description here"></a></p>
  
  <p>Then i try to replot first distribution with mean 10.</p>
  
  <pre><code>output1[1]
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/yMI3D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yMI3D.png" alt="enter image description here"></a></p>
  
  <p>I get the same distibution as before? 
  If however i use the information contained inside the function, return it back and reset it as a global variable it works. </p>
  
  <pre><code>var1=as.numeric(output1[2]);dat=as.data.frame(output1[3]);p1 &lt;- output1[1]
  p1
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/8N1Mt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8N1Mt.png" alt="enter image description here"></a></p>
  
  <p>If anyone can explain why this happens I would like to know. It seems that in order to to draw the intended distribution I have to reset the data.frame and variable to what was used to draw the plot. Is there a way to save the plot as an object without having to this. luckly I can replot the first distribution.</p>
  
  <p>but i can't plot them both at the same time</p>
  
  <pre><code> var1=as.numeric(output2[2]);dat=as.data.frame(output2[3]);p2 &lt;- output2[1]
   grid.arrange(p1,p2)
  </code></pre>
  
  <blockquote>
    <p>ERROR:  Error in gList(list(list(data = list(x = c(9.66707664902549, 11.3631137069225,  : 
      only 'grobs' allowed in "gList"</p>
  </blockquote>
  
  <p>In this" <a href="https://stackoverflow.com/questions/9315611/grid-of-multiple-ggplot2-plots-which-have-been-made-in-a-for-loop">Grid of multiple ggplot2 plots which have been made in a for loop</a> " answer is suggested to use a list for containing the plots </p>
  
  <pre><code> ggplothist&lt;- function(dat,var1)
  {
      if (is.character(var1)) {
              var1 &lt;- which(names(dat) == var1) 
      }
      distribution &lt;- ggplot(data=dat, aes(dat[,var1])) 
      distribution &lt;- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
      plot(distribution)
      pltlist &lt;- list()
      pltlist[["plot"]] &lt;- distribution
      output&lt;-list(pltlist,var1,dat)
      return(output)
  }
  
  output1 &lt;- ggplothist(dat=df,var1='x')
  p1&lt;-output1[1]
  
  output2 &lt;- ggplothist(dat=df2,var1='y')
  p2&lt;-output2[1]
  
  output1[1]
  </code></pre>
  
  <p>Will produce the distribution with mean=100 again instead of mean=10
  and:</p>
  
  <pre><code>grid.arrange(p1,p2)
  </code></pre>
  
  <p>will produce the same Error</p>
  
  <p>Error in gList(list(list(plot = list(data = list(x = c(9.66707664902549,  : 
    only 'grobs' allowed in "gList"</p>
  
  <p>As a last attempt i try to use recordPlot() to record everything about the plot into an object. The following is now inside the function.</p>
  
  <pre><code>    ggplothist&lt;- function(dat,var1)
  {
      if (is.character(var1)) {
              var1 &lt;- which(names(dat) == var1) 
      }
      distribution &lt;- ggplot(data=dat, aes(dat[,var1])) 
      distribution &lt;- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
      plot(distribution)
      distribution&lt;-recordPlot()
      output&lt;-list(distribution,var1,dat)
      return(output)
  }
  </code></pre>
  
  <p>This function will produce the same errors as before, dependent on resetting the dat, and var1 variables to what is needed for drawing the distribution. and similarly can't be put inside a grid. </p>
  
  <p>I've tried similar things like arrangeGrob() in this question "<a href="https://stackoverflow.com/questions/31947727/r-saving-multiple-ggplot2-plots-as-r-object-in-list-and-re-displaying-in-grid">R saving multiple ggplot2 plots as R-object in list and re-displaying in grid</a> " but with no luck.</p>
  
  <p>I would really like a solution that creates an R object containing the plot, that can be redrawn by itself and can be used inside a grid without having to reset the variables used to draw the plot each time it is done. I would also like to understand wht this is happening as I don't consider it intuitive at all. </p>
  
  <p>The only solution I can think of is to draw the plot as a png file, saved somewhere and then have the function return the path such that i can be reused - is that what other people are doing?. </p>
  
  <p>Thanks for reading, and sorry for the long question.</p>