首页 > 解决方案 > 从函数返回图形而不绘制它

问题描述

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

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

标签: rcowplot

解决方案


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 变量中。


推荐阅读