When using color.id from the plotrix package, is it possible to get ONLY a single colour returned not a vector of colours? see this example:
color.id("#A1A295")
this returns: "gray62" "grey62"
Is there a way (or another package) that simply returns a single colour name?
Thanks.
CodePudding user response:
You can modify the function:
color.id2 <- function(col, distinct = FALSE) {
#modified version of the color.id function in the plotrix package, author: Ben Bolker
c2 <- col2rgb(col)
coltab <- col2rgb(colors(distinct = distinct))
cdist <- apply(coltab, 2, function(z) sum((z - c2)^2))
colors(distinct = distinct)[which(cdist == min(cdist))]
}
color.id2("#A1A295", distinct = TRUE)
#[1] "gray62"
You could send the maintainer of the plotrix package a message and suggest replacing the function with this version.
CodePudding user response:
Here is vectorized function based on what Limey said.
get_color_name <- function(color_hex) {
out = vector(length = length(color_hex))
for(i in seq_along(color_hex)) {
out[i] <- color.id(color_hex[i])[1]
}
out
}
get_color_name(rainbow(5))
>[1] "red" "yellow2" "springgreen2" "dodgerblue2" "magenta2"
get_color_name("#A1A295")
>[1] "gray62"