Search code examples
rcolors

Convert hex color code to color name


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.


Solution

  • 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.