# [R] Convert color hex code to color names

Martin Maechler maechler at lynne.stat.math.ethz.ch
Mon Apr 13 19:10:45 CEST 2015

> To add slightly to that:
> What you want to do is write a function that returns the named color that has the smallest difference to your input hex-triplet. But note that color difference is a large topic. Assuming you want to minimize *perceptual* differences, you want to calculate your differences in Lab color space. The function convertColor() has the option to convert hex to Lab. Example:
> convertColor(t(col2rgb("thistle")), from="sRGB", to="Lab", scale.in=255)

> Within Lab space, you can take the Euclidian distance.

> That all said, I can't imagine why one would want to do this in the first place - color triplets are much more convenient than label strings :-)

> B.

About 1-2 years ago, I have improved the

demo("colors", package = "grDevices")

demo in R.... with inspiration from Marius Hofert.

The demo now features a  nearRcolor() function
that was written for somewhat like that purpose.

##' Find close R colors() to a given color {original by Marius Hofert)
##' using Euclidean norm in (HSV / RGB / ...) color space
nearRcolor <- function(rgb, cSpace = c("hsv", "rgb255", "Luv", "Lab"),
dist = switch(cSpace, "hsv" = 0.10, "rgb255" = 30,
"Luv" = 15, "Lab" = 12))
.............
.............

It allows to use different color spaces and a default set of
cutoffs, for defining what  "near" means.

I had thought at the time to make a regular function out of
it, but then did not follow up on myself :-)

Martin Maechler,
ETH Zurich and R core team

> On Apr 13, 2015, at 11:45 AM, Thierry Onkelinx <thierry.onkelinx at inbo.be> wrote:

> > A combination of rgb(), col2rgb() and colors() can gives hex values for the
> > named colors.
> >
> > ir. Thierry Onkelinx
> > Instituut voor natuur- en bosonderzoek / Research Institute for Nature and
> > Forest
> > team Biometrie & Kwaliteitszorg / team Biometrics & Quality Assurance
> > Kliniekstraat 25
> > 1070 Anderlecht
> > Belgium
> >
> > To call in the statistician after the experiment is done may be no more
> > than asking him to perform a post-mortem examination: he may be able to say
> > what the experiment died of. ~ Sir Ronald Aylmer Fisher
> > The plural of anecdote is not data. ~ Roger Brinner
> > The combination of some data and an aching desire for an answer does not
> > ensure that a reasonable answer can be extracted from a given body of data.
> > ~ John Tukey
> >
> > 2015-04-13 17:28 GMT+02:00 Alejo C.S. <alej.c.s at gmail.com>:
> >
> >> Hi all, I want to convert the output of:
> >>
> >>> rainbow(6)
> >>
> >>> [1] "#FF0000FF" "#FFFF00FF" "#00FF00FF" "#00FFFFFF" "#0000FFFF"
> >> "#FF00FFFF"
> >>
> >> To a vector of color names. Any tip?
> >>
> >>