How can I store a list of ggplots to use in multiplot without overwriting previous plots?

arrays, ggplot2, list, r

Solution

If you end up trying to fix things with direct calls to environments, you are probably overcomplicating your code. Here's a simple snippet that may serve as a core for your function:

drawCovs <- function(cd, ncols) {
  require(ggplot2)
  require(reshape2)
  plots=list()
  cmat=list()
  for (i in 1:(length(cd$covmat))) {
    cmat[[i]] <- cd$covmat[[i]]
    plots[[i]] <- ggplot(melt(cmat), aes(x=Var1, y=Var2, fill=value)) + 
                  geom_tile(color='white')
  }  
  multiplot(plotlist=plots,cols=ncols)
}

cd <- list()
cd$covmat <- list(matrix(runif(25), 5), matrix(runif(25), 5))

drawCovs(cd, 1)

Problem

I want to plot some heatmaps of covariance/correlation matrices in a multiplot using an object created from another function (the `cd` parameter below). The covariance matrices are stored in an array of 3 dimensions, so that `cd$covmat[,,i]` calls the ith covariance matrix. Originally I had some issues with this with having the same plot replicated. However, I discovered I had an environment issue. I've tried resolving this several ways, with the code below being the most recent, but I can't figure out why it's not reading it properly. Is there a particular reason for this? I've tried including and excluding the environment parameter (which I hopefully shouldn't need) and I've tried directly using the `cd$covmat[,,i]` in the `aes()` parameter. ``` drawCovs<-function(cd,ncols){ require(ggplot2) coords=expand.grid(x=1:cd$q,y=1:cd$q) climits = c(-1,1)*max(cd$covmat) cd$levels=c(cd$levels,"Total") covtext=ifelse(!(cd$use.cor),'Covariance','Correlation') plots=list() cmat=list() for (i in 1:(nlevels+1)){ cmat[[i]]<-cd$covmat[,,i] .e<-environment plots[[i]]<-ggplot(environment=.e)+geom_tile(aes(x=coords$x,y=coords$y, fill=as.numeric(cmat[[i]]),color='white'))+ scale_fill_gradient(covtext,low='darkblue',high='red',limits=climits)+ylab('') +xlab('')+guides(color='none')+scale_x_discrete(labels=cd$varnames, limits=1:cd$q, expand=c(0,0))+scale_y_discrete(labels=cd$varnames, limits=1:cd$q, expand=c(0,0))+theme(axis.text.x = element_text(angle = 90, hjust = 1))+labs(title=paste0(covtext,"s of data, ",cd$levels[i])) } multiplot(plotlist=plots,cols=ncols) } ```

Original source