Michael
Michael

Reputation: 7397

Heat map colors corresponding to data in R

I have a one dimensional vector of data in R and I want to find heat map colors that correspond to this data. For example:

data = c(12,32,33,41,5)

I then want to find a vector of HEX colors that correspond to that vector - something like higher values have darker colors and lower values have lighter colors or something of that sort.

Are there any packages/functions out there that will do this?

Thanks!

Upvotes: 0

Views: 1839

Answers (1)

Paul Hiemstra
Paul Hiemstra

Reputation: 60984

By a bit of googling, I found the following function on this link:

val2col<-function(z, zlim, col = heat.colors(12), breaks){
 if(!missing(breaks)){
  if(length(breaks) != (length(col)+1)){stop("must have one more break than colour")}
 }
 if(missing(breaks) & !missing(zlim)){
  breaks <- seq(zlim[1], zlim[2], length.out=(length(col)+1)) 
 }
 if(missing(breaks) & missing(zlim)){
  zlim <- range(z, na.rm=TRUE)
  zlim[2] <- zlim[2]+c(zlim[2]-zlim[1])*(1E-3)#adds a bit to the range in both directions
  zlim[1] <- zlim[1]-c(zlim[2]-zlim[1])*(1E-3)
  breaks <- seq(zlim[1], zlim[2], length.out=(length(col)+1)) 
 }
 colorlevels <- col[((as.vector(z)-breaks[1])/(range(breaks)[2]-range(breaks)[1]))*(length(breaks)-1)+1] # assign colors to heights for each point
 colorlevels
}

It seems that is exactly what you are looking for.

Upvotes: 6

Related Questions