Little useless-useful R functions – Looping through variable names and generating plots

[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Facets in ggplot2 are great for showing multiple plots on a single canvas. Assuming this usually covers many scenarios, there might be a case that you would want to save all the combinations of x and y variables in a plot as a file. Useless scenario, and again somehow useful.

Combination of Species and Petal.Width as boxplot

Given a x-variable (in this case Species) we would like to have as much as four plots, each time with different y-variable (in this case Petal.Width). So the combinations would be:

  • Species x Petal.Width
  • Species x Petal.Length
  • Species x Sepal.Width
  • Species x Sepal.Length

Creating a helper function that will take an input string and convert it to variable for boxplot:

# Helper function
Iris_plot <- function(df=iris, y) {
  ggplot(df, aes(x = Species, y = !! sym(y) )) + 
    geom_boxplot(notch = TRUE) +
    theme_classic(base_size = 10)
}

Once we have a helper function defined, loop into the datasets:

# Main loop through the columns and dataset
for(varR in variableR){
  name <- paste0(varR, "_x_Species")
  png(paste0(name, ".png"))
  print(Iris_plot(df=iris, y=varR))
  dev.off()
}

At the end, you will have in your work enviroment (check path by getwd() ) files, each holding the combination of graph.

As always, code is available in at the Github in same Useless_R_function repository.

Happy R-coding!

To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)