4
votes

I'm trying to color a ggplot by a factor that's mostly numerical, like so:

iris %>%
  ggplot(aes(Sepal.Length, Sepal.Width, color = cut(Petal.Length, 0:7))) + 
  geom_point() + 
  scale_color_viridis_d()

What I would like to do is to special-case the (0,1] value and color that in red but to retain the viridis gradient for the remaining values. I know I could change the color on the fly but I wonder if it's also possible to construct a new discrete color palette that has red as its first color and the gradient thereafter, which would make the code a bit more re-usable.

The more general question is therefore: Can one easily add/remove/edit the colors in an existing discrete color palette?

2
To which package does scale_color_viridis_d belong?Jaap
scale_color_manual(values = c("red", viridis::viridis(6)))?seasmith
D'oh, that was way easier than I thought. @seasmith, you want to submit that as an answer?RoyalTS
On second thought: Is there also a way of doing this for a continuous palette?RoyalTS
For a continuous scale, I think you would need to make the call to continuous_scale(); build your custom color scale function and pass it to the palette argumentseasmith

2 Answers

3
votes

This is basically the same as @seasmith's answer, except with the addition of saving the palette to a variable to use later. I do this often for explicitly setting a NA color and then using the palette across multiple plots.

Other packages have similar functions to the viridis ones: for example, you can get ColorBrewer palettes from RColorBrewer::brewer.pal, CartoColor palettes from rcartocolor::carto_pal, or any of the ggthemes ones from functions with the same name as the palette.

library(tidyverse)

plasma_pal <- c("red", viridis::plasma(n = 6))

plasma_pal
#> [1] "red"       "#0D0887FF" "#6A00A8FF" "#B12A90FF" "#E16462FF" "#FCA636FF"
#> [7] "#F0F921FF"

iris %>%
    ggplot(aes(Sepal.Length, Sepal.Width, color = cut(Petal.Length, 0:7))) + 
    geom_point() +
    scale_color_manual(values = plasma_pal)

Created on 2018-04-19 by the reprex package (v0.2.0).

2
votes

Requires a call to scale_color_manual()

iris %>%
  ggplot(aes(Sepal.Length, Sepal.Width, color = cut(Petal.Length, 0:7))) + 
  geom_point() + 
  scale_color_manual(values = c("red", viridis::viridis(6)))