Reputation: 167
In a ggplot2 plot, I want to use the function:
scale_fill_manual(
values = c(
'mediumorchid2',
'gold1',
'red'
)
I know the RGB code colour for 'red': #FF0000
The colors 'mediumorchid2' or 'gold1' also have this kind of code. How can I get it?
Upvotes: 2
Views: 1291
Reputation: 16940
First, you're talking about the hex representation, not the RGB. The RGB representation is three numbers (either between 0 and 1 or 0 and 255) giving the red, green, and blue levels.
To get the RGB representation, you can just use the base function col2rgb()
:
col2rgb('mediumorchid2')
# [,1]
# red 209
# green 95
# blue 238
I have long had a personal convenience function for getting the hex representation, as it's a task I need to do often:
col2hex <- function(x, alpha = "ff") {
RGB <- col2rgb(x)
return(apply(RGB, 2, function(C) {
paste(c("#", sprintf("%02x", C), alpha), collapse = "")
}))
}
col2hex('mediumorchid2')
# [1] "#d15feeff"
Gordon Shumway's excellent answer mentions that apparently there is a package with such a function already! I would recommend that. However, I leave my answer up both for the discussion of RGB vs. hex and in case you don't want a dependency on gplot
.
Upvotes: 3
Reputation: 2056
The gplots package has a function named col2hex()
:
library(gplots)
col2hex("gold1")
"#FFD700"
Upvotes: 5