user126082
user126082

Reputation: 310

How can I loop over values/factors in a variable in ggplot2?

Using the iris dataset..

Sample code and function:

plotfunction <- function(whatspecies){

baz <- iris %>% filter(Species == whatspecies) %>% 
  ggplot(aes(Petal.Width, Petal.Length)) +
  geom_point() +
  labs(title = whatspecies)

ggsave(filename = paste0(whatspecies,".png"), 
       path = getwd())

return(baz)

}

What I'd like to do is to loop over the Species variable to create 3 plots in my working directory. In my real data frame I have many more factors so I was wondering if there is a better way to do this rather than running the function n number of times - as in this instance I only care about modifying/looping over one variable in each graph.

Edit: In my circumstance I require independent plots so I can't use facets or different aesthetics.

Upvotes: 1

Views: 721

Answers (1)

s_baldur
s_baldur

Reputation: 33743

Is this what you are looking for?

library(dplyr)
library(ggplot2)

for (sp in levels(iris[["Species"]])) {
  plotfunction(sp)
}

Upvotes: 1

Related Questions