Reprex of ggsave() with a for loop to generate a number of plots for each of some number of factors in a category.
library(tidyverse)
## load data
data("diamonds")
## get character vector to loop over
cuts <-
diamonds %>%
select(cut) %>%
distinct() %>%
as_vector() %>%
as.character()
## generate plots
for(i in cuts){
print(i)
diamonds %>%
filter(cut == i) %>%
ggplot(aes(x = carat))+
geom_histogram(bins = 30)
ggsave(filename = paste0("diamonds-example-",i,".png"), ## ggsave will automatically save the most recent plot generated
width = 7,
height = 5,
units = "in")
}