assign loop not working for plot

2019-08-23 20:10发布

问题:

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

回答1:

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 of aes as you are passing strings for x and y. Here is a working code:

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
plots <- list()
for (Y in listY){
  z= z+1

  plotx <-  ggplot(dat,
                aes_string(x = dat[[X]], y = dat[[Y]])) +
                geom_boxplot() +
                scale_x_discrete(X) +
                scale_y_continuous(Y)+
                theme_bw()
  plot_name <- paste0("plotx",z)
  plots[[plot_name]] <- plotx

}

Then you can individually plot them using plots["plotx1"]



标签: r ggplot2 assign