Chris Schmitt
Chris Schmitt

Reputation: 33

Using for loop to generate grid of ggplots

I am stuck for the past few days with this problem.

for(i in 1:10){
  nam <- paste("A", i, sep = "")
  p <- ggplot(data=PCdf8, aes(x = 1:nrow(PCdf8), y = PCdf8[,i])) +
    geom_line(colour = "#0072B2", size = 0.5) 
  assign(nam, p)
}

grid.arrange(A1, A2, A3, A4, A5, A6, A7, A9, A10)

My code spits out a grid of the same plot (#10, incidentally) 10 times rather than 10 different plots.

I tried writing them to an empty list, but then the non-grobs are not compatible with grid.arrange(). I have tried removing non-grobs also. I resorted to writing each plot to objects A1 through A10. I have also tried removing "nam" at the end of each loop... Nevertheless, it seems this loop produces 10 objects, A1 though A10, of the same plot, meaning the last plot in the loop is irritatingly written into all objects.

I'd like to scale this up to around 100 plots. So, I would like to do something like:

grid.arrange(A1:A100)

I tried using different combinations of seq() and paste() to no avail.

I have seen similar questions asked here and online, but was not able to find a workable solution.

Thanks.

Upvotes: 3

Views: 1321

Answers (2)

jiang ziqi
jiang ziqi

Reputation: 47

Here you need to change the mapping parameter to aes_string() in funtion ggplot

for(i in 1:10){
nam <- paste("A", i, sep = "")
p <- ggplot(data=PCdf8, mapping = aes_string(x = 1:nrow(PCdf8), y = PCdf8[,i])) +geom_line(colour = "#0072B2", size = 0.5) 
assign(nam, p)
}
grid.arrange(A1, A2, A3, A4, A5, A6, A7, A9, A10)    

Hope this helps.

Upvotes: 0

neilfws
neilfws

Reputation: 33802

I'd suggest a different approach. Reshape your data from wide to long, then use facets.

library(dplyr)
library(tidyr)
library(ggplot2)

# Example data frame
df1 <- as.data.frame(matrix(rnorm(100), ncol = 10, nrow = 10))
df1 %>% 
  mutate(x = 1:nrow(df1)) %>% 
  gather(var, val, -x) %>% 
  ggplot(aes(x, val)) + geom_line() + facet_wrap(~var, ncol = 5)

enter image description here

Upvotes: 3

Related Questions