Frage

I have a matrix of values between -1 and 0 and I'd like to map them to colors of the blend red --> white --> blue. In other words, red is -1, 0 is white, and blue is positive 1.

Next I'd like to grab the rgb values from these colors as three seperate matrices.

War es hilfreich?

Lösung

You could scale your values -1 to +1 to 0 to 1 then use colorRamp. A full function taking a matrix m in and returning an array of r/g/b values would be:

m <- matrix(seq(-1,1,length.out=9),nrow=3)

#      [,1]  [,2] [,3]
#[1,] -1.00 -0.25 0.50
#[2,] -0.75  0.00 0.75
#[3,] -0.50  0.25 1.00

colsel <- function(m,cols) {
  x <- as.vector(m)
  xscal <- scale(x,center=min(x),scale=diff(range(x)))
  out <- colorRamp(cols)(xscal)
  dim(out) <- c(dim(m),3)
  dimnames(out) <- list(NULL,NULL,cols)
  out
}

The result:

colsel(m, c("red","white","blue"))

#, , red
#
#     [,1]   [,2]   [,3]
#[1,]  255 255.00 127.50
#[2,]  255 255.00  63.75
#[3,]  255 191.25   0.00
#
#, , white
#
#       [,1]   [,2]   [,3]
#[1,]   0.00 191.25 127.50
#[2,]  63.75 255.00  63.75
#[3,] 127.50 191.25   0.00
# 
#, , blue
# 
#       [,1]   [,2] [,3]
#[1,]   0.00 191.25  255
#[2,]  63.75 255.00  255
#[3,] 127.50 255.00  255
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top