How do I create a colour scale function in r with a pre-defined scale (like viridis from library("viridis")
?
The question is not how to use it within ggplot, but how to build a function I can feed arbitrary values within the specified value domain to and retrieve the according colour strings (rgb, hex or any other output format) from.
colorRamp
and colorRampPalette
seem to interpolate only between 2 colours within a given colour space. But how would I go about this with viridis for example?
EDIT:
Thanks to @sconfluentus' answer I wrote the following function that does what I want (w/o safety checks):
library("viridis")
number_vector <- c(0.772, 1.235, 5.78, 8.890, 10.543, 14.702)
map_viridis <- function(vec, num) {
vector_expanded <-round(vec, 1) * 10 # expand to allow for decimal precision
vector_exp_range <- max(vector_expanded) - min(vector_expanded)
colour_vector <- viridis(vector_exp_range + 1) # get vector of colour values for all possible decimals between min and max value
value_to_colour <- colour_vector[num * 10 - min(vector_expanded) + 1] # retrieve colour value for number
return(value_to_colour)
}
map_viridis(number_vector, 0.8) # returns "#440154FF"
map_viridis(number_vector, 3.4) # returns "#424086FF"
map_viridis(number_vector, 14.7) # returns "#FDE725FF"
Just wondering if there's not a more direct way to achieve this result?
begin
andend
arguments? For example, withscale_fill_viridis(option = "C", begin = .2, end = .9)
. You want a function to randomly select those values?