13

In ggplot2, we have the option of setting colours by name or hex code. Is there any way to use rgb values in the same way? I searched the docs but the quick answer seems to be 'no'. (The reason I would like to use rgb is that I have some colours that I am going to use for some plots, and I have them all in rgb format. I can get the hex from places like here, but it would be great if I could just enter the values straight into ggplot().

3
  • 5
    What about the function rgb?
    – bouncyball
    Jan 23, 2017 at 17:07
  • 2
    qplot(x=1, fill=I(rgb(0.1, 0.8, 0.5)))
    – Axeman
    Jan 23, 2017 at 17:09
  • Nice! I didn't know about that function. Thanks, Axeman & bouncyball. Jan 23, 2017 at 17:12

1 Answer 1

23

You can use the function rgb(r, g, b) to convert fractional RGB values to hex:

rgb(0.1,0.2,0.3)
[1] "#1A334D"

If your values are based on 8-bit color (or any other limit), you can use the maxColorValue option to specify the maximum number:

rgb(207, 31, 46, maxColorValue = 255)
[1] "#CF1F2E"
1
  • 9
    Great. I used this directly in the plot function, but it needs the maxColorValue argument if you don't have your RGB colours in fractions: scale_colour_manual(values = c(rgb(207, 31, 46, maxColorValue = 255)), "#ffda85")) Jan 23, 2017 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.