首页 > 解决方案 > 如何管理 R 中的颜色对比度以标记图和表?

问题描述

R中的颜色对比如何工作?我假设颜色十六进制值中有一些触发器可以用来帮助判断是否应该将标签的颜色更改为更亮/更暗的颜色。我对一个通用的解决方案很感兴趣——我知道有一些包可以为ggplot2. 我更喜欢一种可以控制颜色对比程度的方法。

这段代码说明了这一点。scales包装处理颜色对比度很好。我只想对它有更多的控制权。

 library(tidyverse)

    library(scales)

    show_col(c("darkred", 
               "wheat", 
               "darkblue", 
               "steelblue"))



tibble(key = letters[1:4], 
       value = 1:4) %>%
  ggplot(aes(key, value))+
  geom_col(aes(fill = key))+
  geom_text(aes(label = key), 
            position = position_stack(vjust = 0.5))+
  scale_fill_manual(values = c("darkred", 
                           "wheat", 
                           "darkblue", 
                           "steelblue")) 

从秤 从秤码

来自 ggplot 来自ggplot图形

标签: rcolorscontrast

解决方案


@Henrik 指出,开源的魔力意味着我可以从scales包中获取并构建代码来实现我的目标。

library(tidyverse)
library(scales)

# Create colour vector
colours <- c("steelblue", 
  "wheat", 
  "darkblue", 
  "darkred") 


### Code from scales package use switch from white/black based on colour specification

## grab matrx of hcl. According to ?hcl, 
## stands for hue, chroma and luminance
hcl <- farver::decode_colour(
  colours, "rgb", "hcl")

## Simple ifelse statement to create binary 
## colour vector based on conditional value
## of luminance that is higher than 50. 
label_col <- ifelse(hcl[, "l"] > 50, "black", "white")


## back to ggplot2 example


## 1) Use borrowed scales code to create a 
## simple wrapper function called contraster
contraster <- function(.colours){
  
  .colurs_hcl <-  farver::decode_colour(
    .colours, "rgb", "hcl")

  ifelse(.colurs_hcl[, "l"] > 50, "black", "white")
}

colours <- c("steelblue", 
             "wheat", 
             "darkblue", 
             "darkred") 

# 2) Now re-create the data and plot
tibble(key = letters[1:4], 
       value = 1:4) %>%
  ggplot(aes(key, value))+
  geom_col(aes(fill = key))+
  geom_text(aes(label = key),
            color = contraster(colours),
            position = 
              position_stack(vjust = 0.5))+
  scale_fill_manual(values = colours) +
  labs(title = "Label colours are now contrasting with the background")

在此处输入图像描述


推荐阅读