从函数返回图形而不绘制图形

用户名

我想编写返回图形的函数,但不应绘制图形。仅在我要求时才绘制图表。

这是MWE。

graph_functions <- function(x) {
  plot(1:length(x), x)
  points(1:length(x), x^2)
  t <- recordPlot()
  return(t)
}

answer <- graph_functions(1:10)

library(cowplot)
plot_grid(answer, answer)

在上面的代码中,当我第一次通过调用计算答案时,我不希望它绘制图graph_functions(1:10)我只想在使用时绘制图表plot_grid()

克劳斯·威尔克

您可以打开一个空设备并对其进行渲染。请注意,如果您将Cowplot与base-R图形一起使用,则应使用升级到开发版本devtools::install_github("wilkelab/cowplot")它提供了对Base-R图形的极大改进。

graph_functions <- function(x) {
  cur_dev <- grDevices::dev.cur()   # store current device
  pdf(NULL, width = 6, height = 6)  # open null device
  grDevices::dev.control("enable")  # turn on recording for the null device
  null_dev <- grDevices::dev.cur()  # store null device

  # make sure we always clean up properly, even if something causes an error
  on.exit({
    grDevices::dev.off(null_dev)
    if (cur_dev > 1) grDevices::dev.set(cur_dev) # only set cur device if not null device
  })

  # plot
  plot(1:length(x), x)
  points(1:length(x), x^2)
  recordPlot()
}

answer1 <- graph_functions(1:10)
answer2 <- graph_functions(1:20)
cowplot::plot_grid(answer1, answer2)

reprex软件包(v0.2.1)创建于2018-12-04

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章