【问题标题】:Cannot create PDF by ggplot2 within if-statements无法在 if 语句中通过 ggplot2 创建 PDF
【发布时间】: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


【解决方案1】:

要使用pdfjpg 函数保存ggplot 对象,必须显式打印ggplot。

if (TRUE) { 
  pdf() 
  print(ggplot()) 
  dev.off()
}

这在R-FAQ 中有说明7.22 为什么格子/格子图形不起作用?

最可能的原因是您忘记告诉 R 显示图表。格函数 例如 xyplot() 创建一个图形对象,但不显示它( ggplot2 图形和 S-PLUS 中的格状图形也是如此)。这 图形对象的 print() 方法产生实际的显示。什么时候 你在命令行交互地使用这些函数,结果 自动打印,但在 source() 或您自己的函数中 您将需要一个明确的 print() 语句。

因此,即使没有条件语句或循环(sourceecho = TRUE 将保存情节),如果只是 source 一个脚本,它也将不保存


我个人更喜欢使用ggsave 函数,因为它看起来更灵活。

if (TRUE) { 
  ggplot() 
  ggave(filename = "plot.pdf")
}

【讨论】:

    猜你喜欢
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2016-09-27
    相关资源
    最近更新 更多