Plots not working in for loop

15,388

Solution 1

When I use print it works:

for(i in 1:15) {   
  pdf(paste("plot", i, ".pdf", sep=""), width=4, height=4)
  abc <- ggplot(mtcars, aes(cyl, disp)) + 
    geom_point(alpha=.6, size=3)
  print(abc)
  dev.off()
}

Solution 2

Or try ggsave:

for(i in 1:15) {   
Filename <- paste("plot", i, ".pdf", sep="")
abc <- ggplot(mtcars, aes(cyl, disp)) + 
    geom_point(alpha=.6, size=3)
ggsave(filename = Filename, abc, width=4, height=4)
}
Share:
15,388

Related videos on Youtube

bill999
Author by

bill999

Updated on June 04, 2022

Comments

  • bill999
    bill999 almost 2 years

    I need to make a bunch of individual plots and want to accomplish this in a for loop. I am using ggplot2. I would just use the facet option if it could save each graph in a separate file, which I don't think it can do.

    There is something going on because the plots are not saved into the files. The files are generated, though, but are empty. Here is an idea of what my code looks like:

    for(i in 1:15) {    
    pdf(paste("path/plot", i, ".pdf", sep=""), width=4, height=4)
    
    abc <- ggplot(data[data[,3]==i,], 
                  aes(variable, value, group=Name, color=Name)) + 
      geom_point(alpha=.6, size=3)+geom_line() + 
      theme(legend.position="none", axis.text.x = element_text(angle = -330)) + 
      geom_text(aes(label=Name),hjust=0, vjust=0, size=2.5) + 
      ggtitle("Title")
    
    abc
    
    dev.off()
    }
    

    How can I save the plots into these files?

    Note that if I has a numeric value and I run the code inside the for loop, everything works.

    • Mehdi Nellen
      Mehdi Nellen about 9 years
      did you try print(abc)?
  • saQuist
    saQuist over 2 years
    Thanks! It worked for me without the dev.off(). With the dev.off() it seemed to clear all the plots, leading to no plots being shown in the end.