I've got a function that uses ggplot. I'd like to either pass it a variable to use for the fill
aesthetic, or use a different colour when I don't pass in anything.
The if/else statement does that for the function below, but my actual function is a bit more complicated and has a few if/else branches, so I'd like to minimise them.
Would it be possible to set the default fill for geom_bar()
to "blue"
, but have that overridden if I pass in a fill
aesthetic?
Alternatively, I was thinking of creating a list of arguments to be passed to geom_bar()
, based on the arguments passed to my function, and splicing it in using !!!
. I haven't really got my head around tidyeval/quasiquotation yet though so I don't quite know how that would work.
I'm open to other solutions too though.
library(ggplot2)
plotter <- function(x = mtcars, fill = NULL) {
p <- ggplot(x, aes(factor(cyl)))
# I don't like this if/else statement
if (!is.null(fill)) {
p <- p + geom_bar(mapping = aes_string(group = fill, fill = fill))
} else {
p <- p + geom_bar(fill = "blue")
}
p
}
plotter()
plotter(fill = "as.factor(gear)")