The colorRamp2 package

Zuguang Gu (z.gu@dkfz.de)

2022-12-21

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.7853539 0.3305331 0.9602919 0.7126902 0.6421130 0.2226382 0.6644241
##  [8] 0.4527759 0.4884661 0.8601798
x2
##  [1] 0.7725624 0.3340315 0.9582373 0.6980786 0.6288315 0.2268344 0.6504547
##  [8] 0.4548796 0.4898490 0.8502995
sessionInfo()
## R version 4.2.0 (2022-04-22)
## Platform: x86_64-apple-darwin17.0 (64-bit)
## Running under: macOS Big Sur/Monterey 10.16
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] C/UTF-8/C/C/C/C
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] colorRamp2_0.1.0
## 
## loaded via a namespace (and not attached):
##  [1] digest_0.6.31    R6_2.5.1         lifecycle_1.0.3  jsonlite_1.8.4  
##  [5] magrittr_2.0.3   evaluate_0.19    highr_0.9        stringi_1.7.8   
##  [9] rlang_1.0.6      cachem_1.0.6     cli_3.4.1        jquerylib_0.1.4 
## [13] bslib_0.4.2      vctrs_0.5.1      rmarkdown_2.19   tools_4.2.0     
## [17] stringr_1.5.0    glue_1.6.2       xfun_0.35        yaml_2.3.6      
## [21] fastmap_1.1.0    compiler_4.2.0   colorspace_2.0-3 htmltools_0.5.4 
## [25] knitr_1.41       sass_0.4.4