Skip to content

detect brightness of hex color value in R / convert from hex to hsl/hsv space how?

4 messages · Mark Heckmann, Achim Zeileis, Michael Friendly +1 more

#
On Fri, 29 Jan 2010, Mark Heckmann wrote:

            
You can use the "colorspace" package for that. hex2RGB() converts a hex 
string to "RGB" coordinates which in turn can be easily converted to 
systems like "HSV" or (preferably) HCL (called "polarLUV" in colorspace).

R> as(hex2RGB("#910322"), "polarLUV")
             L        C        H
[1,] 31.61831 95.14145 6.913428

"L" corresponds to the luminance (whether a color is light or dark), "C" 
is chroma (how colorful the color is compared to a gray with the same 
luminance), and "H" is the hue.

hth,
Z
#
Perhaps some variation of

   SetTextContrastColor <- function(color)
   {
     ifelse( mean(col2rgb(color)) > 127, "black", "white")
   }
Mark Heckmann wrote:

  
    
#
There is a col2grey (and col2gray) function in the TeachingDemos package that use a common algorithm to convert colors to grey based on perceived lightness, that may work for you on deciding the color.

For placing text on colored backgrounds, look at the shadowtext function (also in TeachingDemos) for another way.

Hope this helps,