Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 319
Chris Schmitt Avatar asked Jan 19 '26 13:01

Chris Schmitt


1 Answers

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

like image 130
neilfws Avatar answered Jan 21 '26 04:01

neilfws



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!