1

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)")
Oliver
  • 1,098
  • 1
  • 11
  • 16
  • 1
    See `update_geom_defaults()` for setting the defaults of a geom. Sounds like it might be what you are after. – aosmith Jun 21 '18 at 17:11
  • If that's what you needed, [this question](https://stackoverflow.com/questions/17150303/ggplot2-how-do-i-set-the-default-fill-colour-of-geom-bar-in-a-theme) may be a duplicate. – aosmith Jun 21 '18 at 17:12
  • I think that'd do the trick, but I don't love the idea of updating defaults in my function. I'd have to reset them at the end, and if the function fails halfway through I'd be left with strange defaults. – Oliver Jun 22 '18 at 12:18
  • if you reset geom default in on.exit, it will be reset even if your function fails halfway through. – Ildi Czeller Aug 12 '18 at 09:22

0 Answers0