Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default color scheme in ggplot2?

Tags:

r

ggplot2

I would like to change the default color scheme in ggplot2. That is, I would like to define a color scheme (say: viridis) at the one point in the script so that all subsequent ggplot diagrams will use this color scheme without having to call + scale_color_viridis() each time.

I've seen this SO post featuring update_geom_defaults(geom, new), but I could not find a way to explain this function to use a scheme such as viridis.

I have also tried to update the ggplot color, similar to this post, but, as @baptise pointed out, this approach does not really work.

In short:

  1. define new color scheme, eg., viridis

  2. call ggplot subsequently without adding + scale_color_viridis() but still this ggplot diagram uses the viridis color scheme.

like image 973
Sebastian Sauer Avatar asked Dec 12 '18 19:12

Sebastian Sauer


1 Answers

It looks like

options(ggplot2.continuous.colour="viridis")

will do what you want (i.e. ggplot will look for a colour scale called

scale_colour_whatever

where whatever is the argument passed to ggplot2.continuous.colourviridis in the above example).

library(ggplot2)
opts <- options(ggplot2.continuous.colour="viridis")
dd <- data.frame(x=1:20,y=1:20,z=1:20)

ggplot(dd,aes(x,y,colour=z))+geom_point(size=5)
options(oldopts) ## reset previous option settings

For discrete scales, the answer to this question (redefine the scale_colour_discrete function with your chosen defaults) seems to work well:

scale_colour_discrete <- function(...) {
  scale_colour_brewer(..., palette="Set1")
}
like image 187
Ben Bolker Avatar answered Oct 03 '22 18:10

Ben Bolker