jnordeman
jnordeman

Reputation: 139

Combining scale_colour and scale_fill in same function

I am trying to write a function that would allow me to control both the scale_colour and scale_fill within the same call. However, when I am trying to add the two together in the same function I get this error message: Error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?

Is there a way to overcome this?

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.6.3

dual_scale <- function(){
  scale_color_brewer(palette="Dark2")+
    scale_fill_brewer(palette="Dark2")
}

ggplot()+
  dual_scale()
#> Error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?

Created on 2021-03-25 by the reprex package (v1.0.0)

Upvotes: 3

Views: 346

Answers (1)

teunbrand
teunbrand

Reputation: 37933

This is simply because you cannot use + to combine things in ggplot unless one of the arguments is the plot itself. Instead, you can just wrap the scales in a list, and the + method for a list is to add the elements seperately.

library(ggplot2)

dual_scale <- function(){
  list(
    scale_color_brewer(palette="Dark2"),
    scale_fill_brewer(palette="Dark2")
  )
}

ggplot(mtcars, aes(wt, mpg))+
  geom_point(aes(colour = as.factor(cyl))) +
  dual_scale()

Alternatively, if you truly need 1 scale with the same breaks, labels, titles etc., you can just set a dual-aesthetic scale instead of two separate scales.

dual_scale <- function() {
  scale_colour_brewer(palette = "Dark2", aesthetics = c("colour", "fill"))
}

ggplot(mtcars, aes(wt, mpg))+
  geom_point(aes(colour = as.factor(cyl))) +
  dual_scale()

Created on 2021-03-25 by the reprex package (v1.0.0)

Upvotes: 5

Related Questions