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.
There are two types of color mapping algorithms: those that employ the statistics of the colors of two images, and those that rely on a given pixel correspondence between the images. An example of an algorithm that employs the statistical properties of the images is histogram matching.
In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.
In R, the color black is denoted by col = 1 in most plotting functions, red is denoted by col = 2 , and green is denoted by col = 3 . So if you're plotting multiple groups of things, it's natural to plot them using colors 1, 2, and 3.
Color mapping is the process of mapping values in your data to colors in a plot. It allows you to increase the dimensionality of a graphic - for example, adding a third dimension to the two-dimensional x, y coordinates in a scatterplot.
Here's a map2color function:
map2color<-function(x,pal,limits=NULL){
if(is.null(limits)) limits=range(x)
pal[findInterval(x,seq(limits[1],limits[2],length.out=length(pal)+1), all.inside=TRUE)]
}
map2color(0:11,rainbow(200),limits=c(1,10))
[1] "#FF0000FF" "#FF0000FF" "#FFA800FF" "#ADFF00FF" "#05FF00FF" "#00FFA3FF"
[7] "#00ABFFFF" "#0003FFFF" "#A600FFFF" "#FF00B0FF" "#FF0008FF" "#FF0008FF"
map2color(0:11,rainbow(200))
[1] "#FF0000FF" "#FF8A00FF" "#EBFF00FF" "#61FF00FF" "#00FF29FF" "#00FFB3FF"
[7] "#00BAFFFF" "#0030FFFF" "#5900FFFF" "#E300FFFF" "#FF0091FF" "#FF0008FF"
mypal <- colorRampPalette( c( "blue", "red" ) )( 5 )
x <- c( 1, 9, 8.5, 3, 3.4, 6.2 )
map2color(x,mypal)
"#0000FF" "#FF0000" "#FF0000" "#3F00BF" "#3F00BF" "#BF003F"
I needed something like this to create a colorramp that would be consistent across different samples of data, so I added an xlim parameter. Thanks for the reminder of the findInterval function in your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With