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")) 来自scales

来自ggplot

发布于 2021-03-02 05:07:12
@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")

https://stackoverflow.com/questions/66412685
复制相似问题