This is my code:
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")
}
I don't want to render the plots, I just need to store them as objects so I can then pass them on to a grid of graphs.
There have been similar question made here before, like this one and this one too, but none of the answers provide a solution to my problem. When I run the code, I get this error message: "Error: data
must be a data frame, or other object coercible by fortify()
, not a numeric vector".
EDIT: Gordon observed that I needed to pass a data.frame to ggplot. I've changed x_i
to a data frame, this is code now
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")
}
This has created new questions. I'm getting a single object x_i
, not 4 objects x_1, x_2, x_3, x_4
. The same happened to ``plot_i```. I get this message: replacement element 1 has 100 rows to replace 1 rowsreplacement element 1 has 1000 rows to replace 1 rowsreplacement element 1 has 10000 rows to replace 1 rowsreplacement element 1 has 100000 rows to replace 1 rows