0

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
2
  • 2
    The plot is constructed new when you print it. After the loop, the value of Y is the last value in listY. You have several options: You can substitute dat[[Y]] or you can turn the ggplot object into a grob. Commented Aug 1, 2017 at 6:37
  • This is the correct reason for getting the same plot outside the loop. Commented Aug 1, 2017 at 6:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

sorry if this is a new question but how do I call the plots into cowplot? when I try to run plot.grid(plots[1],plots[2]) it doesnt recognised them as plots
figured it out I needed to used plot_grid(plotlist=plots)
aes_string makes it so you don't need coding like dat[[X]] but can refer to the variable directly. So in this case it could look like aes_string(x = X, y = Y).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.