Plotting Multiple Plots by Grouping Variable Using a For Loop


I have a plotting function that takes as arguments a tibble of data and a specific value of a grouping variable from a column within the tibble. When called, it filters the tibble by the specific value of the grouping variable and then plots some data. It works fine when called individually but I'd like to loop over all the unique values of the grouping variable to create a set of individual plots. I cannot get the function to make plots when called in the for loop. Reprex below (my real problem is a lot more complicated so I can't, for example, use facets instead of the for loop):


#make dataset
dataset_tbl <- tibble(grouping_var = factor(c(rep("cat", 3), rep("dog", 3), rep("bird",3)))) %>% 
  mutate(measurement = c(rnorm(3, mean = 5, sd = 2), 
                         rnorm(3, mean = 10, sd = 2), 
                         rnorm(3, mean = 15, sd = 2)))

#make ploting function
plotting_fct <- function(tbl, g_var){
  tbl %>% 
    filter(grouping_var == g_var) %>%
    ggplot(aes(x = grouping_var, y = measurement)) +

#test plotting function - it works
plotting_fct(tbl = dataset_tbl, g_var = "cat")

#make a list to loop over
list_vec <- dataset_tbl %>% distinct(grouping_var)

#test plotting function on a single subset item of list - it works
plotting_fct(tbl = dataset_tbl, g_var = list_vec$grouping_var[1])

#try to print out 3 plots using for loop - doesn't work
for (i in 1:3){
  plotting_fct(tbl = dataset_tbl, g_var = list_vec$grouping_var[i])

Thank you for your help!

This is not just ggplot, in a for loop the result of computations is not automatically displayed (I don't know the reason though and would be curious if someone here does):

for(i in 1:3){
# nothing on the console

You need to print explicitly:

for(i in 1:3){
[1] 1
[1] 2
[1] 3

Same thing with a ggplot object, it works if you print it explicitly:

for(i in 1:2){
  p <- ggplot(mtcars) +

If you want to save the plots to look at them later, you can also call ggsave().

Oh man I feel silly... I think I actually tried this earlier but your example also made me realize that I had a space between the "for" and the (i in 1:3) so I fixed that too and it works. Thank you!

That's strange, it seems to work for me with a space.

Ahhhh you are right again! I must have changed both at the same time and noticed it ran correctly but I see now the space doesn't matter. It truly was just a matter of telling it to print. Apologies!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.