[R] rgb and col2rgb color conversion/modification/shading

Earl F. Glynn efg at stowers-institute.org
Tue Aug 1 21:21:42 CEST 2006


<ccarey at fhcrc.org> wrote in message 
news:1154392412.44cea15c0c1fa at webmail.fhcrc.org...
>I want to get a lighter shade of a color...I have a lot of colored objects 
>and
> want each one printed as a foreground against a slightly lighter 
> background.
>
> I thought I could try something like changing the alpha channel by first
> converting it to rgb.

I'm not sure what you want to do with the alpha channel - it's sometimes 
used for transparency, especially on Macs, but is not used much on PCs 
(AFAIK).



Let's say you want different shades of gold:

> colors()[142]

[1] "gold"



Instead of RGB color space perhaps you should consider HSV 
(Hue-Saturation-Value) color space.



Let's convert "gold" to rgb to hsv:



> col2rgb( colors()[142] )

      [,1]

red    255

green  215

blue     0



> rgb2hsv( col2rgb( colors()[142] ) )

       [,1]

h 0.1405229

s 1.0000000

v 1.0000000



The "hue" (h) is the color ranging from 0 to 1 around a color circle (with 
red= 0 or 1).  Find h = 0.140 ("gold") in this color circle:



hue <- seq(0.0, 1.0, by=1/40)



pie(rep(1,40),

    labels=formatC(hue, digits=3, format="f"), cex=0.75,

    col=hsv(hue, 1.0, 1.0),

    radius=1.0,

    main="HSV (S=1, V=1)" )




Hues range from 0.0 to 1.0.




A color is saturated (s=1) when it is "far" from a shade of gray (ranging 
from black to white).  Grays are unsaturated (no color) colors with s = 0. 
Saturation ranges from 0.0 to 1.0.



The value (v) is the brightness of the color.  Low values appear quite dark 
but still have color.  v=1 is as bright as possible.   Values range from 0.0 
to 1.0.



You can get different "shades" of the same color by varying changing the 
saturation and value for a given hue.  The hsv function returns the RGB 
color in hex form.



Consider:

> hsv(0.1405, 1, 1)

[1] "#FFD700"



Hex FF = decimal 255 = red

Hex D7 = decimal 215 = green

Hex 00 = decimal 0 = blue



Let's vary Saturation from 0.0 to 1.0 and Value from 0.0 to 1.0 in this 
plot:





MakeHSVRectangle <- function(saturation, value)

{

  GoldHue <- 0.140

  color <- hsv(GoldHue, saturation, value)

  rect(100*saturation, 100*value, 100*saturation+4, 100*value+4, col=color)

}





plot(0:110,0:110, type="n",

     xlab="Saturation[%]", ylab="Value[%]",

     main="Shades of Gold, H=0.140")

outer(seq(0.0, 1.0, 0.05), seq(0.0, 1.0, 0.05), MakeHSVRectangle)





With Value = 0, all colors are "black".  With Saturation=0, the only 
"colors" along the y axis are the shades of gray.  The original "gold" 
rectangle is at the upper right.



So, given a starting color, you have a number of "shades" (various 
saturations and values) with the same color hue.



I hope this helps.



efg

Earl F. Glynn

Scientific Programmer

Stowers Institute for Medical Research



More information about the R-help mailing list