我通常使用的方法是操纵因子值,以便我可以将它们插入hcl()
功能。
首先,一些原始数据:
library(tidyverse)
raw_data <-
diamonds %>%
filter(price < 500, color %in% c("E", "F", "G")) %>%
mutate(
factor = factor(color),
intensity = cut,
interaction = paste(factor, intensity)
)
接下来使用这种争论来获取十六进制颜色:
color_values <-
raw_data %>%
distinct(factor, intensity, interaction) %>%
arrange(factor, intensity) %>%
mutate(
interaction = fct_inorder(interaction),
# get integer position of factors
factor_int = as.integer(factor) - 1,
intensity_int = as.integer(intensity),
# create equal intervals for color, adding in some padding so we avoid extremes of 0, 1
hue_base = factor_int / (max(factor_int) + 0.5),
light_base = 1 - (intensity_int / (max(intensity_int) + 2)),
# using ^^^ to feed into hcl()
hue = floor(hue_base * 360),
light = floor(light_base * 100),
# final colors
hex = hcl(h = hue, l = light)
)
color_values %>% filter(intensity == "Good")
# factor intensity interaction factor_int intensity_int hue_base light_base hue light hex
# <ord> <ord> <fct> <dbl> <int> <dbl> <dbl> <dbl> <dbl> <chr>
# E Good E Good 0 2 0 0.714 0 71 #D89FA9
# F Good F Good 1 2 0.4 0.714 144 71 #81BA98
# G Good G Good 2 2 0.8 0.714 288 71 #BDA4D2
Plot it:
ggplot(df, aes(x, y, color = interaction)) +
geom_count() +
facet_wrap(~factor) +
scale_color_manual(
values = color_values$hex,
labels = color_values$interaction
) +
guides(color = guide_legend(override.aes = list(size = 5)))