Home > Back-end >  How to map numeric vector to hex color codes in R
How to map numeric vector to hex color codes in R

Time:03-08

I'm going to provide an example to make this a little easier. Let's say I have a numeric vector ranging from -2 to 2. I would like to map the numeric values to a color hex code. The colors closer to -2 would be red and the colors close to 2 would be blue. Numeric values close to zero would be grey. So for example the vector below

x <- c(-2,0,2)

would become

x <- c("#FF5733","#8E8E8E","#355EDF")

Obviously I am going to have many numbers between -2 and 2 which is where I am having the issue. Any help appreciated.

CodePudding user response:

You can use colorRamp and rgb:

colfunc <- colorRamp(c("#ff5733", "#838383", "#355edf"))
cols <- colfunc(seq(0,1,len=11))
cols
#        [,1]  [,2]  [,3]
#  [1,] 255.0  87.0  51.0
#  [2,] 230.2  95.8  67.0
#  [3,] 205.4 104.6  83.0
#  [4,] 180.6 113.4  99.0
#  [5,] 155.8 122.2 115.0
#  [6,] 131.0 131.0 131.0
#  [7,] 115.4 123.6 149.4
#  [8,]  99.8 116.2 167.8
#  [9,]  84.2 108.8 186.2
# [10,]  68.6 101.4 204.6
# [11,]  53.0  94.0 223.0

rgb(cols[,1], cols[,2], cols[,3], maxColorValue = 255)
#  [1] "#FF5733" "#E65F43" "#CD6852" "#B47163" "#9B7A72" "#838383" "#737B95" "#6374A7" "#546CBA" "#4465CC" "#355EDF"

plot(1:11, rep(1, 11), col=rgb(cols[,1], cols[,2], cols[,3], maxColorValue = 255), pch=16, cex=3)

enter image description here

The colorRamp returns a function, to which you should pass normalized values (on [0,1]), where 0 prefers the first color and 1 the last. (This means you are responsible for scaling from c(-2,0,2) to c(0,0.5,1).)

  •  Tags:  
  • r
  • Related