You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R混合调色板与亮度变量生成最优区分的十六进制颜色码

R语言实现多调色板混合与亮度调整生成均匀区分度颜色方案

完全可以实现,核心采用LAB颜色空间做颜色混合,相比RGB空间能保证生成的颜色在视觉感知上分布更均匀、区分度更好,最终可以直接导出所有颜色的十六进制编码。

  • 依赖包:colorspace(用于颜色空间转换、均匀调色)、grDevices(R内置包,用于颜色编码转换)

步骤1:安装加载依赖包

# 首次使用执行安装
install.packages("colorspace")
# 加载依赖
library(colorspace)
library(grDevices)

步骤2:定义基础调色板

你可以直接替换下方示例的色值为你自己确定的5阶红色、4阶橙色调色板:

# 5阶红色调色板示例,可直接替换为自定义十六进制色值数组
red_pal <- sequential_hcl(n = 5, h = 10, c = 80, l = c(30, 80))
# 4阶橙色调色板示例,可直接替换为自定义十六进制色值数组
orange_pal <- sequential_hcl(n = 4, h = 30, c = 90, l = c(35, 85))

步骤3:均匀混合生成5×4种基础颜色

采用LAB空间混合保证感知均匀性,避免出现视觉上过于接近的颜色:

# 转换为LAB颜色空间
red_lab <- as(hex2RGB(red_pal), "LAB")@coords
orange_lab <- as(hex2RGB(orange_pal), "LAB")@coords

# 生成所有5×4组合并按比例混合
mix_colors_lab <- expand.grid(red_idx = 1:5, orange_idx = 1:4)
mix_colors_lab <- cbind(mix_colors_lab, t(apply(mix_colors_lab, 1, function(x) {
  w_red <- 0.5 # 红色混合权重,可根据需要调整占比
  w_orange <- 0.5 # 橙色混合权重
  (red_lab[x[1], ] * w_red + orange_lab[x[2], ] * w_orange)
})))
# 转换为十六进制基础混合色
mix_colors_hex <- hex(LAB(mix_colors_lab[, c("L", "A", "B")]))

步骤4:生成4个层级的亮度/透明度调整结果

可根据需求选择亮度调整或透明度调整方案:

方案A:调整亮度(视觉区分度更好,推荐)

# 4个均匀分布的亮度调整系数,数值越小颜色越暗,可自定义调整
light_levels <- c(0.7, 0.85, 1, 1.15)
# 生成所有5×4×4共80种颜色
final_colors <- expand.grid(mix_idx = 1:length(mix_colors_hex), light_idx = 1:4)
final_colors$hex <- apply(final_colors, 1, function(x) {
  col_hsl <- as(hex2RGB(mix_colors_hex[as.integer(x[1])]), "HSL")@coords
  col_hsl[, "L"] <- pmin(pmax(col_hsl[, "L"] * light_levels[as.integer(x[2])], 0), 1)
  hex(HSL(col_hsl))
})

方案B:调整不透明度

# 4个均匀分布的不透明度层级,数值越小越透明,1为完全不透明
alpha_levels <- c(0.4, 0.6, 0.8, 1)
# 生成所有5×4×4共80种颜色
final_colors <- expand.grid(mix_idx = 1:length(mix_colors_hex), alpha_idx = 1:4)
final_colors$hex <- apply(final_colors, 1, function(x) {
  adjustcolor(mix_colors_hex[as.integer(x[1])], alpha.f = alpha_levels[as.integer(x[2])])
})

步骤5:提取十六进制编码

# 验证生成颜色数量,正常输出为80
length(unique(final_colors$hex))
# 打印所有80个颜色的十六进制编码
print(final_colors$hex)

可选:可视化验证区分度

# 绘制所有颜色块查看区分效果
palette(final_colors$hex)
plot(rep(1:4, each = 20), rep(1:20, 4), col = 1:80, pch = 19, cex = 3, axes = F, xlab = "亮度/透明度层级", ylab = "红橙混合色")

内容的提问来源于stack exchange,提问作者denis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:15:07