Little useless-useful R functions – Looping through variable names and generating plots
This article is originally published at https://tomaztsql.wordpress.com
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.
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!
Thanks for visiting r-craft.org
This article is originally published at https://tomaztsql.wordpress.com
Please visit source website for post related comments.