Search code examples
rggplot2colors

How to extract hex code from single named color?


This might be a duplicate (I will remove question if it is), but please read first.

Mock plot:

library(ggplot2)
p <- ggplot(data = mtcars,
       aes(x = hp, y = "", fill = as.factor(gear))
       )+
  geom_boxplot()+
  scale_fill_manual(values = c("#FF3300", "#006600", "purple"))

Note that 2 colors were defined using hex codes, but one was defined using a name recognised by R, "purple".

How do we get the hex color code for what R calls "purple"?

I found several suggestions on SO, none of them works.

Solution 1

ggplot_build(p)$data

Solution 2

g <- ggplot_build(p)
unique(g$data[[1]]["fill"])

Solution 3

ld <- layer_data(last_plot())
(head(ld))

All the above solutions return something like this:

#     fill
#1 #FF3300
#2 #006600
#3  purple 

That is, they do not return the hex code corresponding to "purple".

I know how to return hex codes for entire palettes. But not for a single color, here, "purple".


Solution

  • You can get the rgb code for purple using col2rgb

    > col2rgb("purple")
          [,1]
    red    160
    green   32
    blue   240
    

    Then use those codes in rgb function to get the hex code

    > rgb(160, 32, 240, maxColorValue=255)
    [1] "#A020F0"