I am trying to create several plots (using ggplot2) in a loop and I am using below function.
I used the iris data set and added a random factor variable called "ran_fact. So the data set has now four numerical variables and two factors (Species and ran_fac).
At the moment the loop goes through the numerical variables and creates a plot for each. The two factor variables are set manually (as the plots x-axis and color) inside the loop, which makes it less versatile. I would like to know if it is possible to set the x-axis and color option as a function argument and if yes how that can be done?
Thank you in advance.
Also, as a side question, below select_if(x, is.numeric)
seems not to remove the factor variables from the data set.
library(datasets)
library(dplyr)
library(ggplot2)
library(beeswarm)
data(iris)
iris$ran_fac <- as.factor(c("A", "B", "C", "D", "E"))
plotFunc <- function(x, na.rm = TRUE,...) {
plot_list = list()
nm <- select_if(x, is.numeric)
nm <- names(x)
for (i in seq_along(nm)) {
plots <-ggplot(x,aes_string("ran_fac", nm[i], color="Species")) + geom_quasirandom() + geom_boxplot()
plot_list[[i]] = plots
print(plots)
ggsave(plots,filename=paste("myplot",nm[i],".png",sep=""))
}
}
plotFunc(iris)