Home > Net >  Attempting to plot multiple graphs using `for` in R, but had to do call manually why? - troubleshoot
Attempting to plot multiple graphs using `for` in R, but had to do call manually why? - troubleshoot

Time:11-18

I was attempting to plot multiple boxplots to different variables of my data using a for. I am able to get the plots to be produced, but it only happens manually. So for instance I will execute the for loop and one graph will be created, then I have to do it again and again, etc. Which defeats the purpose of me making the for loop in the first place. I was wondering if this is a software behaviour or am I doing something wrong in my creation of the plots? Here is the code to reproduce things:

> dput(head(Job_Proficiency, 10))
structure(list(job_proficiency = c(88, 80, 96, 76, 80, 73, 58, 
116, 104, 99), T_1 = c(86, 62, 110, 101, 100, 78, 120, 105, 112, 
120), T_2 = c(110, 97, 107, 117, 101, 85, 77, 122, 119, 89), 
    T_3 = c(100, 99, 103, 93, 95, 95, 80, 116, 106, 105), T_4 = c(87, 
    100, 103, 95, 88, 84, 74, 102, 105, 97)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))
> for (i in seq(along = Job_Proficiency)){
      with(data = Job_Proficiency, Boxplot(y = Job_Proficiency[i], xlab = names(Job_Proficiency)[i]))
  }

So as stated before to produce the graphs, I have to execute the for loop manually. Is there a way to correct this? I had envisioned executing the for loop once and all five graphs would be produced.

EDITS: For clarification, I am using R-Studio as my IDE. I also used the Boxplot() function from the car package

CodePudding user response:

If using R-GUI, by default each iteration of the loop will be overwriting the plot display, so only the last one will be visible. If using RStudio, all 5 plots will be created and you can navigate between them in the plot pane.

Or in case you want to see all five at once, you can use the par function to tell R to plot multiple charts side-by-side.

Job_Proficiency <- structure(list(job_proficiency = c(88, 80, 96, 76, 80, 73, 58, 
                                          116, 104, 99), T_1 = c(86, 62, 110, 101, 100, 78, 120, 105, 112, 
                                                                 120), T_2 = c(110, 97, 107, 117, 101, 85, 77, 122, 119, 89), 
                      T_3 = c(100, 99, 103, 93, 95, 95, 80, 116, 106, 105), T_4 = c(87, 
                                                                                    100, 103, 95, 88, 84, 74, 102, 105, 97)), row.names = c(NA, 
                                                                                                                                            -10L), class = c("tbl_df", "tbl", "data.frame"))
par(mfrow = c(1, 5))

for (i in seq(along = Job_Proficiency)){
      boxplot(x = Job_Proficiency[i], xlab = names(Job_Proficiency)[i])
}

par(mfrow = c(1, 5)) basically tells it to plot the charts on a 1 row by 5 column grid.

  • Related