0

I am trying to create three different plots in a for loop and then plotting them together in the same graph. I know that some questions regarding this topic have already been asked. But I do not know what I am doing wrong. Why is my plot being overwritten. Nevertheless, I tried both solutions (creating a list or using assign function) and I do not know why I get my plot overwriten at the end of the loop.

So, the first solution is to create a list:

library(gridExtra)
library(ggplot2)

out<-list()
for (i in c(1,2,4)){
  print(i)
  name= paste("WT.1",colnames(WT.1@meta.data[i]), sep=" ")
  print(name)
  out[[length(out) + 1]] <- qplot(NEW.1@meta.data[i],
                 geom="density",
                 main= name)
  print(out[[i]])
}
grid.arrange(out[[1]], out[[2]], out[[3]], nrow = 2)

When I print the plot inside the loop, I get what I want...but of course they are not together.

First Plot

When I plot them all together at the end, I get the same plot for all of the three: the last Plot I did.

All together

This is the second option: assign function. I have exactly the same problem.

for ( i in c(1,2,4)) {
  assign(paste("WT.1",colnames(WT.1@meta.data[i]),sep="."), 
     qplot(NEW.1@meta.data[i],geom="density",
           main=paste0("WT.1",colnames(WT.1@meta.data[i]))))
 }
pogibas
  • 27,303
  • 19
  • 84
  • 117
ppato
  • 1
  • 1
  • 1
    Please read up on providing a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so it's easier for other users to assist you. – shrgm Oct 04 '17 at 12:46

1 Answers1

1

You're missing to dev.off inside the loop for every iteration. Reproducible code below:

library(gridExtra)
library(ggplot2)

out<-list()
for (i in c(1,2,3)){
  print(i)

  out[[i]] <- qplot(1:100, rnorm(100), colour = runif(100))

  print(out[[i]])
  dev.off()
}
grid.arrange(out[[1]], out[[2]], out[[3]], nrow = 2)

enter image description here

amrrs
  • 6,215
  • 2
  • 18
  • 27