【发布时间】:2019-07-04 05:04:52
【问题描述】:
考虑一个最小的示例:使用 ggplot2 生成一个空图并将其放入 PDF 文件中。通常人们会这样做
pdf()
ggplot()
dev.off()
它按预期工作。但是,当您将这些语句包装到 if 语句中时,生成的 PDF 文件会损坏。
if (TRUE) {
pdf()
ggplot()
dev.off()
}
此问题已在 Windows 10 和 macOS Mojave 上重现。我正在使用最新版本的 R
$ R --version
R version 3.6.0 (2019-04-26) -- "Planting of a Tree"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin18.6.0 (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License versions 2 or 3.
For more information about these matters see
https://www.gnu.org/licenses/.
【问题讨论】:
-
使用
ggsave保存ggplot- 我认为这应该是典型的方法。 -
我认为这通常发生在您缺少
dev.off()时。可能来自在ifelse语句之前执行的pdf()。 -
@Suren 使用
ggsave有效!但是,我在 if 语句中有一个dev.off()。顺便说一句,在每次实验之前我都有rm(lisy=ls())以确保环境干净。 -
我认为你必须这样做
p <- ggplot(); print(p)然后dev.off() -
是的,只有
{}(此处为dev.off())中的最后一条语句被隐式打印,因此您需要显式打印:if (TRUE) { pdf(); print(ggplot()); dev.off()}
标签: r if-statement pdf ggplot2 graphics