首页 > 解决方案 > R/graphics:在函数中绘制为 PNG

问题描述

我想使用一个函数cowplot::plot_grid()直接写入PNG。我可以通过脚本使它工作:

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

但是,如果我在一个函数中尝试这个,它不起作用:

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

这会产生与脚本相同的消息...

RStudioGD 
        2 

...但没有创建文件 mypic2.png。

假设这可能与文件位置有关,我在默认 WD 中的 RStudio 项目之外尝试了相同的代码。同样,mypic1.png 是在标准目录中创建的,但不是 mypic2。显示的消息是不同的(在这两种情况下):

null device
          1

我错过了什么?

标签: rggplot2pngcowplot

解决方案


请让我知道这是你所期待的。

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

原因:在您自己的函数中,您将需要一个显式print()声明。


推荐阅读