2

I write many packages where the generic plot is a ggplot2. A ggplot call, unlike other R function calls, is layered so one could end up with several options (separated by + signs) to get a plot looking just right. However, I don't want someone to suffer through my pre-defined options and would like them to be able to customize it without re-writing my function from scratch. How do I accomplish this?

With a traditional function, I could use the three dot operator to pass optional arguments. This seems harder with a ggplot.

Reproducible example

f <- function(df) {
 custom_plot <-  ggplot(df, aes(mpg, disp, color = gear)) + 
geom_point(size = 3) +  
theme(panel.background = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), panel.border = element_blank(),
        axis.line = element_line(colour = "black"))
        return(custom_plot)
}

To generate a plot

f(mtcars)

produces this:

A test plot

How do I generalize this function such that someone could pass additional or different options to this plot (especially in cases where it is the generic plot)?

If my function were defined as:

f <- function(df, ...)

How would I pass those in to my ggplot call?

2
  • 3
    I gave up writing functions in this style (arguments defining plot options) a while ago, in favor of returning a basic ggplot object that can then be customized via + as needed outside the function. Commented Dec 12, 2012 at 2:53
  • Thanks @joran That's good to know. This was a request from a user and I totally forgot that the resulting object can still be modified outside the function call. Commented Dec 12, 2012 at 6:36

2 Answers 2

6

The plots returned by your functions should be modifiable for anyone who knows ggplot- unless you can think of specific cases that can't be fixed by using +, a better solution might be to do as little theming and customization as possible, and let people add to the plots themselves.

All of these customizations work fine, for example:

mtplot <- f(mtcars)
mtplot + theme_bw()
mtplot + scale_colour_gradientn(colours=c("red", "purple"))
mtplot + labs(title="Add a title!")
mtplot + geom_point(size=5)
Sign up to request clarification or add additional context in comments.

Comments

0
tt <- function(x, ...) {
  ap <- list(...)
  ggplot(x, aes(x = Sepal.Length, y = Petal.Length, colour= Species)) +
    geom_point() +
    ap
}

tt(x = iris)
tt(x = iris, scale_colour_manual(values = c("#da291c", "#64009b", "#127ae3")))
tt(x = iris, scale_colour_manual(values = c("#da291c", "#64009b", "#127ae3")), labs(title = "Example with iris"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.