14

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
  • 8,486
  • 4
  • 33
  • 48
bill999
  • 2,147
  • 8
  • 51
  • 103

2 Answers2

23

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()
}
Mehdi Nellen
  • 8,486
  • 4
  • 33
  • 48
  • 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. – saQuist Nov 03 '21 at 10:35
6

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)
}
AndrewMinCH
  • 710
  • 5
  • 8
  • What is the difference internally, when we use ggsave or the native R device print? Is there any benefit we get using ggsave over the pdf() --> dev.off() process? – Lazarus Thurston Jan 10 '22 at 20:09