【发布时间】:2015-05-27 09:55:16
【问题描述】:
将多个 ggplot2 图存储为 pdf 时,我有一个奇怪的现象。使用 ggsave 存储时,我得到 B_ggplot.pdf 正常,但 A_ggplot.pdf 没有关闭文件(它似乎被锁定)。旧方法有时会生成一个空白页。似乎有比赛条件,但我不能指望它。
谁能帮我理解这个?
代码如下:
library(ggplot2)
# plot A
figureA <- ggplot(data=mtcars, aes(x=cyl, y=hp)) + geom_point()
# plot B
figureB <- ggplot(data=mtcars, aes(x=wt, y=carb)) + geom_point()
# store PDFs using ggplot2
ggsave(file="D:/A_ggplot.pdf") # OK
ggsave(file="D:/B_ggplot.pdf") # PDF with empty page
# store PDFs the old way
pdf(file="D:/A.pdf") # OK
print(figureA)
dev.off()
pdf(file="D:/B.pdf") # hangs and when closing RStudio, writes file
print(figureB)
dev.off()
【问题讨论】:
-
您是否尝试过运行
dev.off()来关闭所有图形设备,直到出现错误? -
这似乎是这样做的,wrt到关闭文件问题。但是,我仍然有 A_ggplot.pdf 的空白 pdf 页面...?
-
我尝试了您的代码,并通过
ggsave(file="D:/A_ggplot.pdf", plot=figureA)和ggsave(file="D:/B_ggplot.pdf", plot=figureB)解决了您的问题。