循环未完成保存pdf [英] Loop does not finish saving pdf

查看:66
本文介绍了循环未完成保存pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个循环.循环的目的是创建许多图并将其另存为 PDF .选择数据的一个子集后,请执行以下操作:

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()

如果我为要绘制的所有数据子集手动执行此操作,则它本身可以工作.如果我循环尝试, PDF 设备会保存很多空"图片.

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.

推荐答案

这是一个常见问题.您需要在for循环中使用 print(...).

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.

这篇关于循环未完成保存pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆