Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

r - Find hexadecimal color for a specific value, given a color scale

I'm struggling with color coding and was hoping you could help. Here is my issue. I have a dummy dataset:

df <- data.frame(x = 1:10, y = sample(1:100, 10, replace = FALSE, set.seed(2021)))

I first want to plot these data, using a specific color scale:

ggplot(data = df, aes(x = x, y = y, fill = y)) +
  geom_point(shape = 21) +
  scale_fill_continuous_divergingx(palette = "RdBu", 
                                   mid = 50, 
                                   rev = TRUE)

Now I would like to use the color that corresponds to, let's say, x = 6 (i.e. y = 70) for another plot. Given certain constraints, I cannot make just another simple ggplot with the same scale to do this, but would instead need to 'hardcode' the hexadecimal value of that specific color, i.e. #e99c8f. Is there a way to do this, so that I can just then use fill = "#e99c8f" in my other plot?

Hardcoding hex values is easy for certain color scales, e.g. viridis, but I haven't found a way to do it with this one, which I need... :/

Thanks for your help!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try with the ggplot_build() function, to get a data.frame with your data and all layers, and see the points to which color they map (fill column):

R> p <- ggplot(data = df, aes(x = x, y = y, fill = y)) +
+  geom_point(shape = 21) +
+  scale_fill_continuous_divergingx(palette = "RdBu", 
+                                   mid = 50, 
+                                   rev = TRUE)
R> x <- ggplot_build(p)
R> x$data
[[1]]
      fill  x  y PANEL group shape colour size alpha stroke
1  #00578C  1  7     1    -1    21  black  1.5    NA    0.5
2  #CBDEEB  2 38     1    -1    21  black  1.5    NA    0.5
3  #ECF1F5  3 46     1    -1    21  black  1.5    NA    0.5
4  #F3D9D6  4 58     1    -1    21  black  1.5    NA    0.5
5  #0772AC  5 12     1    -1    21  black  1.5    NA    0.5
6  #E69C90  6 70     1    -1    21  black  1.5    NA    0.5
7  #EEBCB4  7 64     1    -1    21  black  1.5    NA    0.5
8  #611300  8 99     1    -1    21  black  1.5    NA    0.5
9  #E8A197  9 69     1    -1    21  black  1.5    NA    0.5
10 #4EA4CB 10 23     1    -1    21  black  1.5    NA    0.5

In addition, scale_fill_continuous_divergingx() is internally using RColorBrewer's "RdBu" palette, which you can query the hex colors by:

R> RColorBrewer::brewer.pal(11, "RdBu")
R> scales::show_col(RColorBrewer::brewer.pal(11, "RdBu"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...