0

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.

1
  • Yes it can. The only gotcha is that you need to explicitly print() the ggplot object within the loop. Commented Jun 14, 2022 at 8:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This code works for me thanks very much. I was trying to save with ggsave but I keep getting errors. I know that there are multiple plots and I think that his were I am getting the error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.