Return 未绘制函数的图形

Return graph from function without plotting it

我想编写 returns 图表的函数,但它不应该绘制图表。它应该只在我要求时绘制图表。

这是一个 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().

时绘制图表
graph_functions<- function(x) {
  plot(1:length(x),x)
  points(1:length(x),x^2)
  t<- recordPlot()
  return(t)
}
answer <- c(1:10)
library(cowplot)
plot_grid(graph_functions(answer),graph_functions(answer))

您可以将函数放在 plot_grid() 函数中,并将参数存储在 answer 变量中。

您可以打开空设备并向其呈现。请注意,如果您使用带有 base-R 图形的 cowplot,您应该升级到开发版本,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 package (v0.2.1)

创建于 2018-12-04