Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With ggplot2, how to get color from value?

Tags:

r

ggplot2

Let's say, I'm building a scatter plot using the following:

library(tidyverse)
data_frame(x = rnorm(500), y = rnorm(500), val = rnorm(500)) %>%
    ggplot(aes(x, y, colour = val)) +
    geom_point() +
    scale_colour_gradient2(low = "red", high = "blue", mid = "yellow")

Is there a way to get the hexadecimal color code associated with an arbitrary value (that falls within the range of existing values)? In other words, how to get #ffff00 (yellow) from 0, or what is the color for 0.2?

like image 219
sinQueso Avatar asked Dec 08 '25 08:12

sinQueso


1 Answers

I've no idea how stable or reliable (or even correct) this is, but diving into the guts of a scale object reveals a few things:

> scg = scale_colour_gradient2(low = "red", high = "blue", mid = "yellow")

That creates a scale object. You can call various methods on it. By default it scales values from -1 to 1 (or maybe 0 to 1) so you have to reset it to your data:

> scg$train(d$val)

Then you can do:

> scg$map(0.2)
[1] "#FAF03B"

Note this scale is zero-centred, so red is -max rather than min because -max < min:

> scg$map(c(-max(d$val),min(d$val),0,max(d$val)))
[1] "#FF0000" "#FF4600" "#FFFF00" "#0000FF"

Does that agree with colours on the graph?

like image 90
Spacedman Avatar answered Dec 09 '25 22:12

Spacedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!