How do I generate a mapping from numbers to colors in R?

colors, r

Solution

My colourscheme package on R-Forge does that:

https://r-forge.r-project.org/projects/colourscheme/

its primary purpose is to create functions that map numeric values (not just integer colour numbers) to colours. The vignette is the best documentation once you've got it installed.

Problem

In R, I can easily generate a color ramp, for example colorRampPalette. The following produces a sequence of five colors, from blue to red: ``` > mypal <- colorRampPalette( c( "blue", "red" ) )( 5 ) > mypal [1] "#0000FF" "#3F00BF" "#7F007F" "#BF003F" "#FF0000" ``` How can I easily map a vector of numbers on this palette? Say, I have a vector of numbers between 0 and 10, like this: ``` x <- c( 1, 9, 8.5, 3, 3.4, 6.2 ) ``` I would like a function, say `map2color`, such that when I run `map2color( mypal, x )`, I get ``` #0000FF, #FF0000, #FF0000, #3F00BF, #3F00BF, #BF003F ``` I usually do something like the following ``` mypalette[ findInterval( x, seq( 0, 10, length.out= 6 ), rightmost.closed= T ) ] ``` but maybe there is a better solution OOB, automatically generating a color scale for a numeric vector.

Original source