R/Colors

From QERM Wiki
Jump to: navigation, search

Contents

Colors

Colors in R can be defined by name (blue, black, darkgoldenrod, cornsilk, etc.), according to RGB values, according to HSL and HCL values (variously, permutations of hue, saturation, chroma and luminescence, see: Wikipedia:HSL and HSV and Wikipedia:Munsell color system for more information). Most of these values are freely definable either as decimal values between 0 to 1 or hexadecimal values between 0 and F.

See the colors command for a list of built in colros.

See rgb, hsv and hcl commands for more on defining custom colors.

Here are a few links to handy R color charts:

http://research.stowers-institute.org/efg/R/Color/Chart/
http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf

Color Palettes

See heat.colors, topo.colors, cm.colors, and rainbow for automatic generation of appealing color spectra.

See the RColorBrewer package for predefined palettes of configurable length that can be sequential, diverging, or qualitative. You can play with the options at their website, or here's a short example:

# to change to default palette (the colors you get with col = 1, col = 2, etc.) to a sequnce of 9 colors using the Blue-Green color scheme:
palette( brewer.pal( 9, "BuGn" ) )

# to see all the color schemes using 4 colors:
display.brewer.all( 4 )

For more sophisticated techniques, you can create your own color palette with the colorRamp and colorRampPalette functions. For instance the 'jet color' scheme used in Matlab can be created by:

jet.colors <- 
 colorRampPalette(c("#00007F","blue","#007FFF","cyan","#7FFF7F","yellow","#FF7F00","red","#7F0000"))  

Transparency

AlphaRainbow.jpeg

Many of the functions related to color allow the input of an alpha parameter determining transparency. This often allows an increase in the clarity of the data presented in a plot. The image at right was created using the simple commands:

x=seq(0,2*pi,length=10)
par(mar=rep(0,4))
plot(cos(x),sin(x),col=1,bg=rainbow(10,alpha=.5),pch=21,cex=25,xlim=c(-2,2),ylim=c(-2,2))


Unfortunately, many devices and file formats do not support transparency. Writing the image from R as a PDF is one of the best choices. The image above was created in the Rgui running in Windows and saved as a JPG. PNG files support transparency, but when save as a JPG, it is flattened. If you copy a plot with transparency from the Rgui as a Windows Metafile, you will get emptiness where there should be color.

The col2rgb function is a useful way to add transparency to color with familiar names:

(x <- col2rgb('red')/255) # normally returns on the scale of 0-255, so rescaled
#      [,1]
#red      1
#green    0
#blue     0
mycol <- rgb(x[1,],x[2,],x[3,],alpha=.5)
print(mycol)
[1] "#FF000080"

See Also

R tips

Personal tools