The colorRamp2 package

The colorRamp2() function can generate a color mapping function from a vector of break values and a vector of corresponding colors. Other colors are linearly interpolated in a certain color space.

library(colorRamp2)

col_fun = colorRamp2(c(0, 0.5, 1), c("blue", "white", "red"))
col_fun(seq(0, 1, length = 20))
##  [1] "#0000FFFF" "#522CFFFF" "#7448FFFF" "#8E61FFFF" "#A479FFFF" "#B891FFFF"
##  [7] "#C9A9FFFF" "#DAC1FFFF" "#E9DAFFFF" "#F8F3FFFF" "#FFF5F1FF" "#FFE1D6FF"
## [13] "#FFCDBBFF" "#FFB8A1FF" "#FFA388FF" "#FF8E6EFF" "#FF7756FF" "#FF5E3DFF"
## [19] "#FF3F23FF" "#FF0000FF"
plot(NULL, xlim = c(0, 1), ylim = c(0, 1))
x = seq(0, 1, length = 20)
y = rep(0.5, 20)
points(x, y, pch = 16, col = col_fun(x), cex = 2)

With the color mapping function col_fun, colors can be mapped back to the original numeric values. Note since colors are discrete, the values that are mapped back are not exactly identical to their original values.

x1 = runif(10)
col = col_fun(x1)
x2 = col2value(col, col_fun = col_fun)
x1
##  [1] 0.6620662 0.6075781 0.4101641 0.3502383 0.5119359 0.4965971 0.1616852
##  [8] 0.2717462 0.2641635 0.1892543
x2
##  [1] 0.6482715 0.5970937 0.4130482 0.3534538 0.5106535 0.4958798 0.1652400
##  [8] 0.2751686 0.2686708 0.1915691
sessionInfo()
## R version 4.4.2 (2024-10-31)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 24.04.1 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
## LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so;  LAPACK version 3.12.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=C              
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## time zone: Etc/UTC
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] colorRamp2_0.0.1 rmarkdown_2.29  
## 
## loaded via a namespace (and not attached):
##  [1] digest_0.6.37     R6_2.5.1          fastmap_1.2.0     xfun_0.49        
##  [5] maketools_1.3.1   cachem_1.1.0      knitr_1.49        htmltools_0.5.8.1
##  [9] buildtools_1.0.0  lifecycle_1.0.4   cli_3.6.3         sass_0.4.9       
## [13] jquerylib_0.1.4   compiler_4.4.2    sys_3.4.3         tools_4.4.2      
## [17] evaluate_1.0.1    bslib_0.8.0       colorspace_2.1-1  yaml_2.3.10      
## [21] jsonlite_1.8.9    rlang_1.1.4