Last active
December 19, 2015 06:29
-
-
Save jokergoo/5911450 to your computer and use it in GitHub Desktop.
linear interpolation between colors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
color.pal = function(x, col = c("green", "black", "red"), breaks = c(-5, 0, 5)) { | |
if(length(col) != length(breaks)) { | |
stop("Length of col should be equal to the length of breaks.\n") | |
} | |
# change col represented as strings to RGB space | |
col_section = sapply(col, function(x) as.vector(col2rgb(x))) | |
col_section = t(col_section) | |
x[x >= max(breaks)] = max(breaks) | |
x[x <= min(breaks)] = min(breaks) | |
color = character(length(x)) | |
for(i in 1:length(x)) { | |
# NA values, grey color | |
if(!is.numeric(x[i])) { | |
color[i] = rgb(128, 128, 128, maxColorValue = 255) | |
next | |
} | |
value = x[i] | |
# find which interval the value belongs to | |
interval = which(breaks >= x[i])[1] | |
if(length(interval) == 0) { | |
interval = length(interval) | |
} | |
if(interval == 1) { | |
interval = 2 | |
} | |
# linear interpolation | |
col_num = (value - breaks[interval])*(col_section[interval, ] - col_section[interval - 1, ]) / (breaks[interval] - breaks[interval - 1]) + col_section[interval, ] | |
col_num = ifelse(col_num > 255, 255, col_num) | |
col_num = ifelse(col_num < 0, 0, col_num) | |
color[i] = rgb(col_num[1], col_num[2], col_num[3], maxColorValue = 255) | |
} | |
return(color) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment