【问题标题】:Saving plots made in a for loop保存在 for 循环中制作的图
【发布时间】:2018-09-13 22:47:23
【问题描述】:

这是我的代码:

library(ggplot2)

for(i in 1:4) {

x_i = vector()  
x_i = rnorm(n = 10^(1+i))

plot_i <- ggplot(data = x_i, aes(x = x_i)) +
geom_histogram(aes(y = ..density..), binwidth = .05, col = "blue") +
stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col = "Red") 

}

我不想渲染绘图,我只需要将它们存储为对象,然后我可以将它们传递到图形网格。

以前这里也有过类似的问题,比如this onethis one too,但没有一个答案能解决我的问题。当我运行代码时,我收到以下错误消息:“错误:data 必须是数据框,或者由fortify() 强制转换的其他对象,而不是数字向量”。

编辑:Gordon 观察到我需要将 data.frame 传递给 ggplot。我已将x_i 更改为数据框,现在是代码

library(ggplot2)

for(i in 1:4) {


x_i[,1] = data.frame(rnorm(n = 10^(1+i)))

plot_i <- ggplot(data = x_i, aes(x = x_i)) +
geom_histogram(aes(y = ..density..), binwidth = .05, col = "blue") +
stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col = "Red") 

}

这产生了新的问题。我得到一个对象x_i,而不是4 个对象x_1, x_2, x_3, x_4。 ``plot_i``` 也是如此。我收到此消息:替换元素 1 有 100 行替换 1 行替换元素 1 有 1000 行替换 1 行替换元素 1 有 10000 行替换 1 行替换元素 1 有 100000 行替换 1 行

【问题讨论】:

  • 就像错误消息说你需要给 ggplot 一个数据框作为输入。 x_i 当前被定义为向量而不是数据框
  • 谢谢,我已经编辑了问题

标签: r for-loop ggplot2


【解决方案1】:

正如错误消息所述,ggplot 需要一个数据框作为输入,而您提供 x_i 这是一个数字向量。要解决这个问题,只需将向量设为数据框中的一列。要存储所有图,请创建一个列表,并在每次迭代时将 ggplot 对象添加到列表中。然后,您可以使用列表作为晶格的输入。

library(ggplot2)
plots <- list()
for(i in 1:4) {

  x_i = data.frame("V1" = rnorm(n = 10^(1+i)))

  plots[[i]] <- ggplot(data = x_i, aes(x = V1)) +
    geom_histogram(aes(y = ..density..), binwidth = .05, col = "blue") +
    stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col = "Red") 

}

【讨论】:

  • 为了加快速度,(仅当您制作大量绘图时才重要),为您的列表预先分配内存是明智的。换句话说,通过将plots &lt;- list() 更改为plots &lt;- vector("list", 4) 来指定列表的长度。
【解决方案2】:

就像@Gordon 所说,您需要将 ggplot 传递给 data.frame 而不是 vector。然后你可以在循环中使用ggsave() 来保存你的情节。

for(i in 1:4) {

  x_i = vector()  
  x_i = rnorm(n = 10^(1+i))

  plot_i <- ggplot(data = data.frame(x_i=x_i), aes(x = x_i)) +
    geom_histogram(aes(y = ..density..), binwidth = .05, col = "blue") +
    stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col = "Red") 

  ggplot2::ggsave(plot_i, filename = paste0("plot_",i,".png"))

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 2015-08-28
    • 2019-10-24
    相关资源
    最近更新 更多