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!




[…] article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here) […]
LikeLike
[…] Source link […]
LikeLike
Hi Tom,
Thanks for this post,
Great to save plots!.
quick Q:
How to modify the function:
for(varR in variableR){
name <- paste0(varR, "_x_Species")
png(paste0(name, ".png"))
print(Iris_plot(df=iris, y=varR))
dev.off()
}
so that the plots are displayed directly in Rstudio ?,
(not saved as files…).
Just learning R.
Thanks!.
Joe
SF
latest R, Rstudio, Ubuntu Linux.
LikeLike
Hello Tomaz,
Thanks for the useless-useful tip here.
I realised `library(rlang)` was needed to run `y = !! sym(y)` but when I ran the whole lot, this message appears:
“Error in variableR : object ‘variableR’ not found”
I’m also new-ish to R, so wondered if I need to substitute `variableR` with something else – or do I need another library open?
Thanks in advance,
Stuart
R version 4.1.0 (2021-05-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)
RStudio:
$version
[1] ‘1.4.1717’
$release_name
[1] “Juliet Rose”
LikeLike
Nice Post Oracle Cloud Automated Testing Tool
LikeLike