1

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

Pedro Cavalcante
  • 414
  • 4
  • 14

2 Answers2

1

Like @Gordon said, you need to pass ggplot a data.frame rather than a vector. Then you can use ggsave() in the loop to save your plot.

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"))

}
Rich Pauloo
  • 7,734
  • 4
  • 37
  • 69
1

As the error message states ggplot expects a data frame as input while you provide x_i which is a numeric vector. To fix that just make the vector a column in a data frame. To store all the plots create a list and on each iteration add the ggplot object to the list. you can then use the list as input to your lattice.

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") 

}
GordonShumway
  • 1,980
  • 13
  • 19
  • 1
    For a speedup boost, (only important if you're making lots and lots of plots), it's wise to pre-allocate memory for your list. In other words, specify the length of the list by changing `plots <- list()` to `plots <- vector("list", 4)`. – Rich Pauloo Sep 13 '18 at 23:14