r - 如何管理 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"))
解决方案
@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")
推荐阅读
- c# - 有没有办法监视一个方法是否使用 Moq.NET 捕获了异常?
- activemq-artemis - 只有只读控制台权限的用户?
- windows - WinHttpSendRequest 失败,错误代码 87
- c - 尝试将值复制到指针 str 时获取 null
- swift - Swift Unit Test 如何使用私有设置器进行设置
- python - 如何使用数据框中的列在新数据框中创建行?
- android - 我刚刚将 Firebase 添加到我的 Unity 项目中,现在出现 Gradle Build Failed 错误
- python-3.x - 如何包含循环或乘以循环直到满足精度?
- python - Python - TypeError:“NoneType”对象不可下标
- apache-spark - 如何加载火花模型