3

Q: Is it possible to set scale_color_viridis in the theme of ggplot2 so that users don't have to explicitly write + scale_color_viridis()?

By default, ggplot2 can automatically figure out the proper palette without the user specifying discrete or continuous. For example, both of the following codes would work with same geom_point(color=xxx):

Discrete variable:

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) + geom_point(aes(color=Species)) category

Continuous variable:

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) + geom_point(aes(color=Petal.Width)) enter image description here

My purpose is to replace the default "black-blue" gradient colormap with virdis, so that I can enjoy both the smartness of ggplot2 and my own preference of colors.

enter image description here


Update:

With the hints from @jdobres, and bqast's Gist I managed to make it work by doing:

scale_colour_continuous <- viridis::scale_color_viridis ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +geom_point(aes(color=Petal.Width))

Puriney
  • 2,417
  • 3
  • 20
  • 25
  • 2
    Possibly already answered here: https://stackoverflow.com/questions/9944246/setting-defaults-for-geoms-and-scales-ggplot2 – jdobres Feb 02 '18 at 23:01

1 Answers1

1

As MLavoie pointed out you need to override the palette one way or another.

Another option, instead of adding scale_color_viridis(), is using scale_colour_gradientn:

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
  geom_point(aes(color=Petal.Width))+
  scale_colour_gradientn(colors=viridis(3))

enter image description here

If you need to use it often, you can store your scale (scale_colour_gradientn or scale_color_viridis) and save some typing later:

scv <- scale_color_viridis()
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
  geom_point(aes(color=Petal.Width),size=2)+ scv
mpalanco
  • 12,960
  • 2
  • 59
  • 67