R语言:如何让plotrix包color.id返回单一HEX对应颜色名称?
解决plotrix包color.id返回多个颜色名称的问题
直接处理现有结果
plotrix::color.id返回"gray62"和"grey62"只是美式与英式拼写的差异,对应同一种颜色。你可以直接提取向量中的单个元素来得到唯一结果:
library(plotrix) # 取第一个结果 single_color <- color.id("#A1A295")[1] # 或指定提取美式/英式拼写 single_gray <- grep("gray", color.id("#A1A295"), value = TRUE) single_grey <- grep("grey", color.id("#A1A295"), value = TRUE)
替代方案:自定义函数或其他包
如果想从根源上避免返回多个结果,可以自己实现一个仅返回最匹配单一颜色名称的函数,利用R基础包grDevices的功能:
get_single_color_name <- function(hex) { target_rgb <- grDevices::col2rgb(hex) named_colors <- grDevices::colors() named_rgb <- t(grDevices::col2rgb(named_colors)) # 计算欧氏距离找最接近的颜色 distances <- sqrt(rowSums((named_rgb - target_rgb)^2)) named_colors[which.min(distances)] } # 调用示例 get_single_color_name("#A1A295")
也可以使用colorspace包通过色差计算来精准匹配:
library(colorspace) get_single_color <- function(hex) { target <- hex2RGB(hex) named_rgb <- lapply(grDevices::colors(), hex2RGB) # 用CIEDE2000色差公式计算距离 distances <- sapply(named_rgb, function(x) deltaE(target, x, method = "CIE2000")) grDevices::colors()[which.min(distances)] } # 调用示例 get_single_color("#A1A295")
内容的提问来源于stack exchange,提问作者POGB
相关产品推荐
相关产品推荐

