将图存储为 R 中的变量

Storing plots as variables in R

你好 Stack 社区,

对于我的项目,我在 R 中可视化脉冲响应函数图。我试图将每个图存储为 R 中的 object(请参阅代码的第 1 部分)以便稍后附加所有图在一个图中(使用 cowplot 库),作为一个分面图(参见代码的第 2 部分)。然而,代码的最终结果是一个空图表,顶部只有标题。

我相信空图的原因应该是 R 将我的图存储为空 objects

非常感谢你的帮助。

R 代码如下:

#PART 1: Making IRF plots and storing them as objects

plot.1 <- plot(irf(df, impulse = "abc", response = "abc", n.ahead = 8, ortho = TRUE, runs = 1000, seed = 1))
plot.2 <- plot(irf(df, impulse = "abc", response = "def", n.ahead = 8, ortho = TRUE, runs = 1000, seed = 1))
plot.3 <- plot(irf(df, impulse = "abc", response = "ghi", n.ahead = 8, ortho = TRUE, runs = 1000, seed = 1))
plot.4 <- plot(irf(df, impulse = "abc", response = "jkl", n.ahead = 8, ortho = TRUE, runs = 1000, seed = 1))

#PART 2: making facet

library(cowplot)
plot_grid(plot.1, plot.2, plot.3, plot.4, rremove("x.text"), 
          labels = c("A", "B", "C", "D"),
          ncol = 2, nrow = 2)

这会有所帮助。

(我还不能评论..所以请随时删除它,因为这不是答案。)

您不能在 R 中以这种方式直接存储绘图。与 R 中的大多数其他函数不同,plot 泛型将绘图绘制为 副作用,并且通常会这样做不是 return 一个可以用来重新创建绘图的对象(对象 plot.1plot.2 等所需要的)来执行您希望它们在此处执行的操作。

为了让它们在 cowplot 中工作,您需要将绘图调用包装在将绘制绘图的 函数 中,并将它们传递给 cowplot::ggdraw.

当然,我没有你的数据,所以将在这里展示一个使用基本 R 图的简单示例

library(gridGraphics)
library(cowplot)

plot1 <- ggdraw(function() plot(x = 1:10, y = 1:10))
plot2 <- ggdraw(function() plot(x = 1:10, y = 10:1))
plot3 <- ggdraw(function() plot(x = 1:10, y = c(1:5, 5:1)))
plot4 <- ggdraw(function() plot(x = 1:10, y = c(10:6, 6:10)))

plot_grid(plot1, plot2, plot3, plot4, labels = LETTERS[1:4])

1) recordPlot 使用recordPlot 记录每个图。

library(cowplot)
library(irtoys)

plot(irf(Scored2pl, items=c(2,3,7)), co=NA, ask = FALSE); plot1 <- recordPlot()
plot(irf(Scored2pl), co="red", label=TRUE, ask = FALSE); plot2 <- recordPlot()
plot(irf(Scored2pl), co="blue", label=TRUE, ask = FALSE); plot3 <- recordPlot()
plot(irf(Scored2pl), co="green", label=TRUE, ask = FALSE); plot4 <- recordPlot()

plot_grid(plot1, plot2, plot3, plot4, labels = LETTERS)

2) formula cowplot 也接受一个公式。输出同上。

library(cowplot)
library(irtoys)

plot1 <- ~ plot(irf(Scored2pl, items=c(2,3,7)), co=NA)
plot2 <- ~ plot(irf(Scored2pl), co="red", label=TRUE)
plot3 <- ~ plot(irf(Scored2pl), co="blue", label=TRUE)
plot4 <- ~ plot(irf(Scored2pl), co="green", label=TRUE)

plot_grid(plot1, plot2, plot3, plot4, labels = LETTERS)