Using png function not working when called within a function

后端 未结 2 832
暖寄归人
暖寄归人 2021-01-03 19:37

I have a function that does stuff and then plots based on a condition:

f <- function(n) {
  rand <- rnorm(n)
  no   <- seq_len(n)
  df   <- data.         


        
2条回答
  •  轮回少年
    2021-01-03 19:57

    From responses, here are two solutions:

    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)
    

    Note: I was aware that I needed to use print(), but the way I tried this didn't work because it wasn't placed in the right place.

    Also, I had tried the ggsave option previously, but that didn't work either. Of course, it now works as well. It also seems to have a better resolution than using 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)
    

    Thanks all.

提交回复
热议问题