Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the default color palette for ggplot2

Tags:

r

ggplot2

I am trying to reverse the color map for a plot using scale_color_brewer(direction = -1). However, doing so also changes the palette.

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

# reverse colors
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
  scale_color_brewer(direction = -1)

Potential solution

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
scale_color_brewer(direction = -1, palette = ?)
like image 922
Ben Avatar asked Aug 24 '17 18:08

Ben


1 Answers

The default color palette ggplot uses is scale_color_hue.

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

is equivalent to

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

direction = -1 does reverse the colors. But then you need to adjust the starting point in the hue wheel, in order to get the same three colors in reversed order.

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
  scale_color_hue(direction = -1, h.start=90)

Each color moves the hue pointer 30 degrees. So we set the starting point at 90.

hue wheel

BTW, in order to let scale_colour_brewer work for categorical variables, you need to set type = 'qual':

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species))+geom_point()+
  scale_color_brewer(type = 'qual', palette = 'Dark2')
like image 100
Polor Beer Avatar answered Sep 18 '22 04:09

Polor Beer