Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop does not finish saving pdf [duplicate]

Tags:

r

ggplot2

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.

like image 382
user3230046 Avatar asked Sep 09 '26 23:09

user3230046


1 Answers

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.
like image 149
jlhoward Avatar answered Sep 12 '26 16:09

jlhoward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!