Each iteration of the loop creates a new plotx. This works fine as when I run print(plotx) it produces a different graph.
I then used assign to call each plot "plotx1","plotx2" etc..to save each plot as a separate name. When I then plot the names plots they are all identical to Y=c BUT the y axis is correctly labelled with the original Y for the loop! Whats going on? How do I correct this?
dat = data.frame("d"= rep(c("bla1","bla2","bla3"),3),"a" = c(1:9), "b"=
c(19:11), "c"=rep(c(3,2,2),3))
X = "d"
listY = c("a","b","c")
z= 0
for (Y in listY){
z= z+1
plotx= ggplot(dat,
aes(x = dat[[X]], y = dat[[Y]])) +
geom_boxplot() +
scale_x_discrete(X) +
scale_y_continuous(Y)+
theme_bw()
print(plotx)
plot_name = paste0("plotx",z)
assign(plot_name , plotx)
}
plotx1
plotx2
plotx3
The reason for this behavior is explained by @Roland. You should use a list to store the plots if you want to access them later. In addition, you should be using
aes_string
instead ofaes
as you are passing strings forx
andy
. Here is a working code:Then you can individually plot them using
plots["plotx1"]