Zhiqiang Wang
Zhiqiang Wang

Reputation: 6759

using simple numbers to assign colors in ggplot2

I wonder if it is possible to create a number system to assign colors in different graphs, something like col = 1 rather than color = "red". I don't really mind about specific colors used as long as they are consistent between graphs. I feel that numbers might be easier to work with than strings when on many graphs. For example, I would like to the following 3 graphs to have the same color for class = "compact":

library(tidyverse) 
#1
mpg %>% 
  ggplot(aes(displ, hwy, col = class)) +
    geom_point() 
# 2
mpg %>% 
  filter(!class %in% c("2seater", "pickup")) %>% 
      ggplot(aes(displ, hwy, col = class)) +
        geom_point()
# 3    
mpg %>% 
  filter(class == "compact") %>% 
  ggplot(aes(displ, hwy)) + 
  geom_line(color = "?")

Upvotes: 0

Views: 676

Answers (1)

neilfws
neilfws

Reputation: 33772

One way to ensure that the same color maps to a specific variable is to use scale_color_manual() with a named vector of colors, where the names are the variables.

For example, you can assign the values of mpg$class to a palette of 7 colors using purrr::set_names:

library(ggplot2)
library(purrr)

group.colors <- set_names(rainbow(7), unique(mpg$class))

group.colors
    compact     midsize         suv     2seater     minivan      pickup  subcompact 
"#FF0000FF" "#FFDB00FF" "#49FF00FF" "#00FF92FF" "#0092FFFF" "#4900FFFF" "#FF00DBFF"

Now compact will always be red.

mpg %>% 
  ggplot(aes(displ, hwy, col = class)) +
  geom_point() +
  scale_color_manual(values = group.colors)

enter image description here

mpg %>% 
  filter(!class %in% c("2seater", "pickup")) %>% 
  ggplot(aes(displ, hwy, col = class)) +
  geom_point() +
  scale_color_manual(values = group.colors)

enter image description here

Upvotes: 2

Related Questions