首页 > 解决方案 > ggplot 按因子和渐变着色

问题描述

我正在尝试绘制一个在两个变量(一个因子和一个强度)上着色的图。我希望每个因素都是不同的颜色,并且我希望强度是白色和该颜色之间的渐变。

到目前为止,我已经使用了诸如对因子进行刻面、将颜色设置为两个变量之间的交互、将颜色设置为因子并将 alpha 设置为强度以近似我想要的技术。然而,我仍然觉得在一个情节上白色和全色之间的渐变最能代表这一点。

有谁知道如何在不自定义创建所有颜色渐变并仅设置它们的情况下做到这一点?此外,有没有办法让图例像使用颜色和 alpha 一样工作,而不是像在为交互设置颜色时那样列出所有颜色?

到目前为止,我已经尝试过:

ggplot(diamonds, aes(carat, price, color=color, alpha=cut)) +
  geom_point()

ggplot(diamonds, aes(carat, price, color=interaction(color, cut))) +
  geom_point()

ggplot(diamonds, aes(carat, price, color=color)) +
  geom_point() +
  facet_wrap(~cut)

我想要实现的是看起来最像使用 alpha 的图形,但不是透明度,我想要白色和那种颜色之间的渐变。此外,我希望图例看起来像使用颜色和 alpha 的图例,而不是交互图中的图例。

标签: rggplot2

解决方案


我通常使用的方法是操纵因子值,以便我可以将它们插入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

绘制它:

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)))

在此处输入图像描述


推荐阅读