How can I translate a hex representation of a color to its corresponding name?
For example, consider the following colors:
rainbow(4)
# "#FF0000FF" "#80FF00FF" "#00FFFFFF" "#8000FFFF"
What are their names (hoping a name exist for each code)?
I discovered the function col2rgb()
but it does not exaclty what I am needing.
You may use the convenience function color.id
from the plotrix
package*:
Given a color specified as a hex string, find the closest match in the table of known (named) colors.
library(plotrix)
sapply(rainbow(4), color.id)
# $`#FF0000FF`
# [1] "red" "red1"
#
# $`#80FF00FF`
# [1] "chartreuse" "chartreuse1"
#
# $`#00FFFFFF`
# [1] "cyan" "cyan1"
#
# $`#8000FFFF`
# [1] "purple"
*Credits to Jim Lemon and his answer here: Convert color hex code to color names.
Perhaps not the most elegant solution, but it should get the job done:
color.names <- function(d) {
# get RGB components of d and convert to data frame
z2 <- as.data.frame(t(col2rgb(d)))
# get RGB components of standard colors and convert them to data frame
z <- as.data.frame(t(sapply(colors(distinct=T),col2rgb)))
colnames(z) <- colnames(z2)
z$name <- rownames(z)
# EDIT: original answer used 'merge', which messed up the order
library(dplyr)
z2 %>% left_join(z) %>% select(name)
}
color.names(rainbow(4))
# name
# 1 red
# 2 <NA>
# 3 cyan
# 4 <NA>
The function color.names
uses the same input as col2rgb
, i.e.
vector of any of the three kinds of R color specifications, i.e., either a color name (as listed by colors()), a hexadecimal string of the form "#rrggbb" or "#rrggbbaa" (see rgb), or a positive integer i meaning palette()[i].
so you can use it to get the names of standard colors by doing color.names(1:8)
For computational efficiency, data set with standard colors can be precalculated as in this example:
init.color.names <- function() {
z <- as.data.frame(t(sapply(colors(distinct=T),col2rgb)))
colnames(z) <- colnames(z2)
z$name <- rownames(z)
library(dplyr)
function(d) {
z2 <- as.data.frame(t(col2rgb(d)))
z2 %>% left_join(z) %>% select(name) }
}
cl <- init.color.names()
cl(1:3)
cl(rainbow(4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With