1

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.

4
  • You can just plot it once with multiple colors aes(color = Species) or facets facet_wrap(~ Species) Commented Oct 16, 2018 at 10:15
  • @PoGibas In my circumstance I require independent plots so I can't use facets or different aesthetics. Commented Oct 16, 2018 at 10:17
  • 1
    @PoGibas he can but that's not what is being asked about. Commented Oct 16, 2018 at 10:17
  • @snoram I understand, just wanted to make sure that this is not a simplest solution. Commented Oct 16, 2018 at 10:19

1 Answer 1

1

Is this what you are looking for?

library(dplyr)
library(ggplot2)

for (sp in levels(iris[["Species"]])) {
  plotfunction(sp)
}
Sign up to request clarification or add additional context in comments.

Comments

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.