assign loop not working for plot

不问归期 提交于 2019-12-25 11:09:11

问题


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"]



来源:https://stackoverflow.com/questions/45430325/assign-loop-not-working-for-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!