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.7560962 0.1761086 0.6080999 0.4737585 0.4718923 0.4753464 0.9088412
## [8] 0.4129385 0.5357165 0.4664550
x2## [1] 0.7424875 0.1783978 0.5970937 0.4754850 0.4732437 0.4754850 0.9034110
## [8] 0.4150489 0.5321333 0.4671428
sessionInfo()## R version 4.3.3 (2024-02-29)
## Platform: x86_64-apple-darwin20 (64-bit)
## Running under: macOS 26.3.1
##
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRlapack.dylib; LAPACK version 3.11.0
##
## locale:
## [1] C/zh_CN.UTF-8/zh_CN.UTF-8/C/zh_CN.UTF-8/zh_CN.UTF-8
##
## time zone: Asia/Shanghai
## tzcode source: internal
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] colorRamp2_0.1.1
##
## loaded via a namespace (and not attached):
## [1] digest_0.6.35 R6_2.5.1 fastmap_1.1.1 xfun_0.43
## [5] cachem_1.0.8 knitr_1.45 htmltools_0.5.8.1 rmarkdown_2.26
## [9] lifecycle_1.0.4 cli_3.6.2 sass_0.4.9 jquerylib_0.1.4
## [13] compiler_4.3.3 highr_0.10 tools_4.3.3 evaluate_0.23
## [17] bslib_0.7.0 colorspace_2.1-0 yaml_2.3.8 rlang_1.1.3
## [21] jsonlite_1.8.8