在函数内调用时使用png函数不起作用

ima*_*gan 22 plot r ggplot2

我有一个功能,可以根据条件执行操作然后绘制:

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)
Run Code Online (Sandbox Code Playgroud)

我在这结尾处得到一个空白的png文件.这里发生了什么?

ima*_*gan 19

从回复中,这里有两个解决方案:

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)
Run Code Online (Sandbox Code Playgroud)

注意:我知道我需要使用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)
Run Code Online (Sandbox Code Playgroud)

谢谢大家.


小智 11

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

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

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