1

Given a numerical value Im trying to find the corresponding color in a ggplot legend; essentially the legend in reverse. I will try a simplified motivating example:

df <- data.frame(x = rnorm(11, mean = .2, sd = .1), y = rnorm(11, mean = -.2, sd = .2))

now plot the data

d <- ggplot(df, aes(x, y)) + 
       geom_point() + 
       geom_raster(aes(fill = seq(from = -1, to = 1, by = .2)))
d

enter image description here

I now want to know what hex color code corresponds to the value at .2 from the legend (or do this for any other value in the range -1,1). I realize that for this example this seems a bit silly; in reality Im making a shared legend for a scientific image and I need to extract the hex colors backwards from the legend.

Ive tried extracting the legend with g_legened(); however, the data structure is complex and I am stuck.

library(lemon)
legend <- g_legend(d)

the envisioned function would be hexColor <- reverseLegend(legend,.2) and assistance would be appreciated.

markus
  • 25,843
  • 5
  • 39
  • 58
nak3c
  • 439
  • 1
  • 6
  • 18

1 Answers1

0

The easiest is probably to manually define your colors in a first place. The following threads help:

For assigning the colors to the values

To manually create the color sequence

Note I have used geom_tile instead of geom_raster. Also I have used scale_fill instead of using a vector within aes - this way you don't create some legend that may not be linked to your data. Also I set limits within scale_fill

I am intending to look for a way to look up the color values - but this is probably the most straight forward option.

library(ggplot2)

df <- data.frame(x = rnorm(11, mean = .2, sd = .1), y = rnorm(11, mean = -.2, sd = .2))

vec_break <- seq(-1,1,0.2) #use any sequence
colfunc <- grDevices::colorRampPalette(c("light blue", "dark blue")) # the choice of colors is yours!
vec_col <- colfunc(length(vec_break))

ggplot(df, aes(x, y)) + 
  geom_tile(aes(fill = y)) +
  scale_fill_gradientn(breaks = vec_break, colors = vec_col, limits = c(-1,1))

Created on 2020-01-28 by the reprex package (v0.3.0)

tjebo
  • 21,977
  • 7
  • 58
  • 94