You can also use the colorRamp
function from base R to map the values to RGB colors and then use the rgb
function to convert to hexadecimal format.
An example :
# I use hex numbers between 0.3 and 0.7 (instead of O and 1) to show that the ggplot scale used the
# minimum and maximum values by defaults (as done in the python examples you provided)
set.seed(123)
d <- data.frame(
hex = sort(runif(20, 0.3, 0.7)),
x = 1:20,
y = 1
)
# Graph with ggplot and scale_fill_gradient2
ggplot(d, aes (x, y, fill = hex)) + geom_bar(stat = "identity") +
scale_fill_gradient2 (low = "red", mid = "white", high = "blue", midpoint = 0.5)
# Normalize the vector to use the minimum and maximum values as extreme values
hexnorm <- (d$hex - min(d$hex)) / (max(d$hex) - min(d$hex))
# Map the hex values to rgb colors
mycols <- colorRamp(c("red", "white", "blue"), space = "Lab")(hexnorm)
# Transform the rgb colors in hexadecimal format
mycols <- rgb(mycols[,1], mycols[,2], mycols[,3], maxColorValue = 255)
mycols
# Check that you obtain the same result as the scale_fill_gradient2 ggplot function
ggplot(d, aes (x, y)) + geom_bar(stat = "identity", fill = mycols)