I have a numeric vector and I would like to convert it to hex color codes. The colors should follow a gradient distribution from its possible minimum (red; 0), via a mid value which I define (the mean, black), to its possible max (green; 1).
With ggplot I would use the scale_*_gradientn
function. But now I need the actual hex values, and I am struggling to calculate them.
library(tidyverse)
#> Warning: package 'dplyr' was built under R version 3.6.2
data <- data.frame("a"=runif(100),
"b"=runif(100))
# ggplot example ----------------------------------------------------------
data <- data.frame("a"=runif(100),
"b"=runif(100))
mean_a <- mean(data$a)
ggplot(data)+
geom_point(aes(x=a,
y=b,
color=a),
stat="identity")+
scale_color_gradientn(colors=c("red","black","green"),
values=c(0, mean_a, 1))+
theme(legend.position = NULL)
Mapping the scale_color_gradientn
function is apparently not the way forward:
data %>%
mutate(color_values=map(a, scale_color_gradientn,
colors=c("red","black","green"),
values=c(0, mean_a, 1))) %>%
head()
#> a b color_values
#> 1 0.2863037 0.9902960 <environment: 0x000000001d002f30>
#> 2 0.6169960 0.9527580 <environment: 0x000000001d038798>
#> 3 0.3126825 0.8807853 <environment: 0x000000001d06e098>
#> 4 0.5464037 0.2307841 <environment: 0x000000001d0a39a8>
#> 5 0.5162976 0.8147066 <environment: 0x000000001d0d92a8>
#> 6 0.7519632 0.6821084 <environment: 0x000000001d10cc98>
Created on 2020-02-17 by the reprex package (v0.3.0)
I came across this SO entry on the colorRamp
function, however, it seems that it does not provide any option to define a manual 'mid' point.
I also came accross this post on colorspace
package, which allows for the definition of a midpoint. However, again, I fail to apply it outside of ggplot.
Grateful for any hint!