I'd like to use ggplot to plot a series of graphs and then stack them using grid.arrange. The problem is that ggplot doesn't "use" the data supplied until grid.arrange is called, which forces me to store the data in .GlobalEnv, and I can't figure out how to avoid conflicting names. To illustrate with an MWE:
library(ggplot2)
library(gridExtra)
plot.one.graph <- function(data)
{
p <- ggplot(data, aes(x = category, y = value))
p <- p + geom_bar(alpha = 0.5, stat = "identity")
se.minus <- data$value - 1 # fake error bar
se.plus <- data$value + 1
assign("se.minus", se.minus, globalenv())
assign("se.plus", se.plus, globalenv())
p <- p + geom_errorbar(aes(ymin = se.minus, ymax = se.plus))
return(p)
}
data.list <- list( data.frame(category = 1:10, value = rnorm(10, 5)),
data.frame(category = 1:10, value = rpois(10, 5)))
ps <- list()
for (i in 1:len(data.list)) {
ps[[i]] <- plot.one.graph(data.list[[i]])
}
grid.arrange(ps[[1]], ps[[2]])
Here I have two data.frame's and I want to plot them one on top of another. The output looks like this
. 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 .GlobalEnv but nothing seems to work. Any suggestions?

1:len(data.list)should probably be1:length(data.list)or evenseq_along(data.list)andps <- list()would be better asps <- vector("list", length(data.list)).