Maiasaura
Maiasaura

Reputation: 32996

How does one pass additional parameters to a ggplot generated inside a function?

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?

Upvotes: 2

Views: 953

Answers (2)

qfazille
qfazille

Reputation: 1671

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"))

Upvotes: 0

Marius
Marius

Reputation: 60210

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)

Upvotes: 6

Related Questions