GegznaV
GegznaV

Reputation: 5590

Wrap several ggplot2 functions and use the wrapper with operator "+" in R

I start with the question: is there a way to create a function, say ggColors, which wraps several other functions from package ggplot2? That function should add up with ggplot object using operator + (and not %>% operator) as in this example:

p <- ggplot(mtcars, aes(hp,disp, color = as.factor(cyl))) + geom_point()
p + ggColors()

Where ggColors should be something like this:

ggColors <- function(values = NULL, name = NULL, cold.colors = TRUE) {
    # Some conditions:
    if (is.null(values)){
        if (cold.colors) {
            values <- c("darkblue","blue", "green")
        } else {
            values <- c("red","orange", "yellow")
        }
    }     
    # Modified default values of `ggplot2` functions:
    scale_color_manual(name = name, values = values) +
    scale_fill_manual (name = name, values = values)
}

The problem is that scale_color_manual and scale_fill_manual do not add up, as they do not result in ggplot object inside the function ggColors.

Upvotes: 2

Views: 360

Answers (1)

eipi10
eipi10

Reputation: 93851

ggColors should return a list of plot elements. Then all of the elements of the returned list can be added to a plot using +:

  ggColors <- function(values = NULL, name = NULL, cold.colors = TRUE) {
    # Some conditions:
    if (is.null(values)){
      if (cold.colors) {
        values <- c("darkblue","blue", "green")
      } else {
        values <- c("red","orange", "yellow")
      }
    }     
    # Modified default values of `ggplot2` functions:
    return(list(scale_color_manual(name = name, values = values),
                scale_fill_manual (name = name, values = values)))
  }

Then,

p + ggColors()

Upvotes: 3

Related Questions