title: How to use make multiple plots with ggplot using the same function?
body: <p>I'd like to use <code>ggplot</code> to plot a series of graphs and then stack them using <code>grid.arrange</code>. The problem is that <code>ggplot</code> doesn't "use" the data supplied until <code>grid.arrange</code> is called, which forces me to store the data in <code>.GlobalEnv</code>, and I can't figure out how to avoid conflicting names. To illustrate with an MWE:</p>
  
  <pre><code>library(ggplot2)
  library(gridExtra)
  
  plot.one.graph &lt;- function(data)
  {
      p &lt;- ggplot(data, aes(x = category, y = value))
      p &lt;- p + geom_bar(alpha = 0.5, stat = "identity")
  
      se.minus &lt;- data$value - 1  # fake error bar
      se.plus &lt;- data$value + 1
      assign("se.minus", se.minus, globalenv())
      assign("se.plus", se.plus, globalenv())
      p &lt;- p + geom_errorbar(aes(ymin = se.minus, ymax = se.plus))
  
      return(p)
  }
  
  data.list &lt;- list(  data.frame(category = 1:10, value = rnorm(10, 5)),
                      data.frame(category = 1:10, value = rpois(10, 5)))
  
  ps &lt;- list()
  for (i in 1:len(data.list)) {
      ps[[i]] &lt;- plot.one.graph(data.list[[i]])
  }
  grid.arrange(ps[[1]], ps[[2]])
  </code></pre>
  
  <p>Here I have two <code>data.frame</code>'s and I want to plot them one on top of another. The output looks like this <img src="https://i.stack.imgur.com/5lxjA.png" alt="output">. Because the latter loop overwrites the (fake) error bar data for the first loop, the error bars were correct for the second graph but wrong for the first. I have tried various ways of storing the variable in <code>.GlobalEnv</code> but nothing seems to work. Any suggestions?</p>