fmic_
fmic_

Reputation: 2446

With ggplot2, how to get color from value?

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?

Upvotes: 3

Views: 306

Answers (1)

Spacedman
Spacedman

Reputation: 94237

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?

Upvotes: 7

Related Questions