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.
When I plot them all together at the end, I get the same plot for all of the three: the last Plot I did.
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]))))
}