3

I am writing a loop. The purpose of the loop is to create many plots and save them as a PDF. After selecting a subset of my data I do the following:

    pdf("path to the desired filename", width = 16, height = 7)

          some ggplot operations...

    dev.off()

This in itself works if I do it manually for all the subsets of data that I want to plot. If I try this in a loop the PDF device saves a lot of "empty" pictures.

I don't understand why this will not work in a loop. It seems like the loop does not wait until the plot has been properly exported.

zx8754
  • 52,746
  • 12
  • 114
  • 209
user3230046
  • 51
  • 1
  • 2
  • You're not going to get any useful answers unless you give us a reproducible example. See: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – josliber Jan 24 '14 at 01:49

1 Answers1

22

This is a common problem. You need to use print(...) inside a for loop.

pdf("myfile.pdf")
for (i in 1:2) {
  ggplot(mpg, aes(x=cty, y=hwy))+geom_point()
}
dev.off()   #  myfile.pdf is empty (no pages)

pdf("myfile.pdf")
for (i in 1:2) {
  print(ggplot(mpg, aes(x=cty, y=hwy))+geom_point())
}
dev.off()   #  myfile.pdf has 2 pages.
jlhoward
  • 58,004
  • 7
  • 97
  • 140