【发布时间】: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 one 和this 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 当前被定义为向量而不是数据框
-
谢谢,我已经编辑了问题