How to set ggplot global color themes using RColorBrewer palettes
Asked Answered
N

1

3

I am trying to set up a global ggplot2 color scheme in my global RMarkdown files and I had success with viridis with the following code

options(
  ggplot2.continuous.colour = "viridis",
  ggplot2.continuous.fill = "viridis"
)
scale_colour_discrete = scale_colour_viridis_d
scale_fill_discrete = scale_fill_viridis_d

However, when I try to use a similar procedure with RColorBrewer, I was unable to do so with default color still showing up. What changes should I make for it to work?

options(
  ggplot2.continuous.colour = "brewer",
  ggplot2.continuous.fill = "brewer"
)
scale_colour_discrete = scale_colour_brewer(palette="Dark2")
scale_fill_discrete = scale_fill_brewer(palette="Dark2")

Namecalling answered 1/7, 2021 at 3:15 Comment(0)
I
4

Discrete

If you wish to specify a default, discrete colour scale such as that produced by scale_colour_brewer() use the ggplot2.discrete.colour option. Similarly, use the option ggplot2.discrete.fill for a discrete fill scale.

Default Discrete Scales

library(ggplot2)

ggplot(mtcars, aes(hp, mpg, color = factor(cyl), fill = factor(cyl))) + geom_point()

Created on 2021-07-01 by the reprex package (v1.0.0)

Custom Discrete Scales

library(ggplot2)

scale_colour_brewer_d <- function(..., palette = "Dark2") {
  scale_colour_brewer(..., palette = palette )
}

scale_fill_brewer_d <- function(..., palette = "Dark2") {
  scale_fill_brewer(..., palette = palette)
}

options(
  ggplot2.discrete.colour = scale_colour_brewer_d,
  ggplot2.discrete.fill = scale_fill_brewer_d
)

ggplot(mtcars, aes(hp, mpg, color = factor(cyl), fill = factor(cyl))) + geom_point()

Created on 2021-07-01 by the reprex package (v1.0.0)

Continuous

If you wish to specify a default, continuous color scale, you will need to use scale_colour_distiller() instead of scale_colour_brewer(). Similarly, use scale_fill_distiller() as opposed to scale_fill_brewer() for a continuous fill scale. You will also use the options ggplot2.continuous.colour and ggplot2.continuous.fill respectively.

Default Continuous Scales

library(ggplot2)

ggplot(mtcars, aes(hp, mpg, color = cyl, fill = cyl)) + geom_point()

Created on 2021-07-01 by the reprex package (v1.0.0)

Custom Continuous Scales

library(ggplot2)

scale_colour_brewer_c <- function(..., palette = "Dark2") {
  scale_colour_distiller(..., palette = palette )
}

scale_fill_brewer_c <- function(..., palette = "Dark2") {
  scale_fill_distiller(..., palette = palette)
}

options(
  ggplot2.continuous.colour = scale_colour_brewer_c,
  ggplot2.continuous.fill = scale_fill_brewer_c
)

ggplot(mtcars, aes(hp, mpg, color = cyl, fill = cyl)) + geom_point()

Created on 2021-07-01 by the reprex package (v1.0.0)

Ibis answered 1/7, 2021 at 6:24 Comment(1)
Thank you very much! The answer is perfect!Namecalling

© 2022 - 2024 — McMap. All rights reserved.