【问题标题】:Using png function not working when called within a function在函数中调用时使用 png 函数不起作用
【发布时间】:2016-04-24 08:50:06
【问题描述】:

我有一个函数可以做一些事情,然后根据条件进行绘图:

f <- function(n) {
  rand <- rnorm(n)
  no   <- seq_len(n)
  df   <- data.frame(no=no, rand=rand)
  if (n > 10) {
    png("plot.png")
    p <- ggplot(df)
    p + geom_point(aes(x=no, y=rand))
    dev.off()
  }
}

f(11)

最后我得到一个空白的 png 文件。这是怎么回事?

【问题讨论】:

  • 这是一个FAQ,无论如何你都应该使用ggsave
  • 我们需要一个faq 包,它具有爬取网络并根据引用对条目进行排名的功能。默认的 R 启动消息会显示一个随机的常见问题解答,我们中的一些人可能会使用 fortune()
  • @baptise 您是否编写了脚本来执行此操作?我实际上认为这将是一个很棒的主意:) +1

标签: r plot ggplot2


【解决方案1】:

根据回复,有两种解决方案:

library(ggplot2)
f <- function(n) {
  rand <- rnorm(n)
  no   <- seq_len(n)
  df   <- data.frame(no=no, rand=rand)
  if (n > 10) {
    png("plot.png")
    print({
      p <- ggplot(df)
      p + geom_point(aes(x=no, y=rand))
    })
    dev.off()    
  }
}

f(11)

注意:我知道我需要使用print(),但我尝试的方法不起作用,因为它没有放在正确的位置。

另外,我之前尝试过ggsave 选项,但也没有用。当然,它现在也可以正常工作。似乎也比使用png() 有更好的分辨率:

library(ggplot2)
f <- function(n) {
  rand <- rnorm(n)
  no   <- seq_len(n)
  df   <- data.frame(no=no, rand=rand)
  if (n > 10) {
    p <- ggplot(df)
    p + geom_point(aes(x=no, y=rand))
    ggsave(file="plot.png")
  }
}

f(11)

谢谢大家。

【讨论】:

  • 您可以接受自己的答案。向所有人展示您的问题已得到解决。
  • 仅供参考,您可以使用 png() 设置所需的分辨率。例如,如果您想要 300 dpi 和 6 英寸见方的图像,您可以调用 png('plot.png', height = 6, width = 6, res = 300, units = 'in')
【解决方案2】:

我刚刚从其他网站了解到(下面提供了链接)。在循环中,您必须显式使用 print 函数才能使 jpeg()、png() 函数正常工作。 在原始帖子中,您只需添加一行 print(p)。

  if (n > 10) {
        png("plot.png")
        p <- ggplot(df)
        p + geom_point(aes(x=no, y=rand))
        print(p)
        dev.off()
    }

在下面的链接中,它对此提供了很好的解释 https://stat545-ubc.github.io/block017_write-figure-to-file.html#despair-over-non-existent-or-empty-figures

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多