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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With