Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using png function not working when called within a function

Tags:

plot

r

ggplot2

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.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)

I get a blank png file at the end of this. What is going on here?

like image 633
imanuelcostigan Avatar asked Feb 09 '12 06:02

imanuelcostigan


2 Answers

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.

like image 131
imanuelcostigan Avatar answered Nov 03 '22 12:11

imanuelcostigan


I just learned from other website (link provided below). In a loop you have to explicitly use print function in order to make jpeg(), png() function to work. In the original post, you can just add a line of print(p).

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

In the link below, it provides a good explanation for this https://stat545-ubc.github.io/block017_write-figure-to-file.html#despair-over-non-existent-or-empty-figures

like image 13
Zhengyu Pang Avatar answered Nov 03 '22 12:11

Zhengyu Pang