6

I have an ordered factor variable that I would like to plot using ggplot2. Is there any way I can use scale_color_viridis(), a continuous color scale, with this ordered factor without casting the factor to numeric? The straightforward

iris$Sepal.Width <- ordered(iris$Sepal.Width)

ggplot(iris, aes(Sepal.Length, Petal.Length, color=Sepal.Width)) + 
  geom_point() + 
  scale_color_continuous()

doesn't work.

RoyalTS
  • 9,545
  • 12
  • 60
  • 101
  • What's wrong with casting it to numeric? Can you please delete the same question with different title. – mtoto Mar 10 '17 at 21:42

2 Answers2

13

Viridis has a discrete = TRUE option.

iris$Sepal.Width <- ordered(iris$Sepal.Width)

ggplot(iris, aes(Sepal.Length, Petal.Length, color=Sepal.Width)) + 
geom_point() + 
viridis::scale_color_viridis(discrete = TRUE)
detroyejr
  • 1,094
  • 1
  • 9
  • 14
3

Last version of {ggplot2} (dev: 2.2.1.9000) now has a viridis scale included.
You can use scale_colour_viridis_d() for discrete values or scale_fill_viridis_c() for continuous values.

In your case :

iris$Sepal.Width <- ordered(iris$Sepal.Width)

ggplot(iris, aes(Sepal.Length, Petal.Length, color=Sepal.Width)) + 
  geom_point() + 
  scale_colour_viridis_d()
Sébastien Rochette
  • 6,536
  • 2
  • 22
  • 43