Home > OS >  R/graphics: Plotting to PNG in function
R/graphics: Plotting to PNG in function

Time:10-27

I want to use a function to have cowplot::plot_grid() write directly to a PNG. I can make it work from a script:

  g <- ggplot2::ggplot(datasets::iris, ggplot2::aes(x = Sepal.Length, y= Sepal.Width))   ggplot2::geom_point()
  
  grDevices::png(filename = "mypic1.png", width = 1000, height = 1000, units = "px", bg = "transparent")
  cowplot::plot_grid(g)
  grDevices::dev.off()

However, if I try this within a function, it doesn't work:

  pxPrint <- function(ggobject, fn, x = 1000, y = 1000) {
    
    grDevices::png(filename = fn, width = x, height = y, units = "px", bg = "transparent")
    cowplot::plot_grid(ggobject)
    grDevices::dev.off()
  }

  pxPrint(ggobject = g, fn = "mypic2.png")

This produces the same message as the script...

RStudioGD 
        2 

...but no file mypic2.png is created.

Assuming this might have to do something with the file locations, I tried the same code outside my RStudio project in my default WD. Again, mypic1.png was created in the standard directory, but not mypic2. The message displayed was different though (in both cases):

null device
          1

What am I missing?

CodePudding user response:

Kindly let me know this is what you were anticipating.

g <- ggplot2::ggplot(datasets::iris, ggplot2::aes(x = Sepal.Length, y= Sepal.Width))   ggplot2::geom_point()

pxPrint <- function(ggobject, fn, x = 1000, y = 1000) {

  grDevices::png(filename = fn, width = x, height = y, units = "px", bg = "transparent")
  print((cowplot::plot_grid(ggobject)))
  grDevices::dev.off()
}

pxPrint(ggobject = g, fn = "mypic2.png")

Reason: Inside your own functions you will need an explicit print() statement.

  • Related