Home > Mobile >  For loop to plot multiple variables in R
For loop to plot multiple variables in R

Time:06-15

I have ran code where I first filter variables and then run a plot, see code below

pl1 = mydata %>%
  filter(CID =="1", NID =="1", SID =="301", WID =="1")
  
ggplot(pl1, aes(x=Timestamp, y=T_Var , colour=SID))   
  geom_line()  
  geom_hline(yintercept=.4, linetype="dashed", color = "red")   
  geom_hline(yintercept=.7, linetype="dashed", color = "maroon")

Were each of the of the filtered items are as follows CID from 1 - 30 NID from 1 - 8 SID from 301 - 310 WID from 1 - 9 T_Var is the target variable

I know this is a lot of plots, but I was wondering if this can be done with a for loop.

CodePudding user response:

I propose this:

for(cid in 1:30) {
  for(nid in 1:8) {
   data <- mydata %>% filter(CID==cid, NID==nid, ...)
   p <- ggplot(mydata ....)
   print(p) # Or save to file using ggsave(), png() or pdf()
  }
}

While filtering you should check if it is necessary to convert number to strings. I dont know what type is you dataframe columns. So instead of filter(CID==cid), you need to write filter(CID==as.character(cid).

Maybe there is a cleaner way to do it. Stacking multiple for loop can make the combinatorial explode... You can also use layout panels (https://ggplot2.tidyverse.org/reference/facet_grid.html) to make multiple subplots but with the number of plots you want to build, it might be non appropriate.

  • Related