If I want to create a list of ggplot objects, then every new plot overwrites the old plot. It is similar to what was asked here. Though I was able to solve the issue using lapply, but I am still not able to figure out why the plots are getting overwritten inside the loop.
library(ggplot2)
trash <- data.frame(matrix(rnorm(100), nrow = 50, ncol = 2))
colTrash <- data.frame(matrix(rnorm(100), nrow = 50, ncol = 2))
##Overwritten: both plots are same
pltList <- list()
for(i in 1:2){
pltList[[i]] <- ggplot(trash)+
geom_point(aes(X1,X2,color = colTrash[,i]))
}
#Not Overwritten: plots are different and correct
pltList <- lapply(1:2, function(i){
ggplot(trash)+
geom_point(aes(X1,X2,color = colTrash[,i]))
})