Nicki_NZ
Nicki_NZ

Reputation: 173

Hexadecimal codes for R built in colours

How do I find out what the hexadecimal codes are for the built in colours in R? For example, I would like to know what the hexadecimal code is for tomato3 Thanks

Upvotes: 2

Views: 1472

Answers (1)

Mikael Jagan
Mikael Jagan

Reputation: 11306

Here's a function that you can use to convert built-in colour names (see ?colors) to hex codes, optionally preserving alpha values:

x <- c("tomato3", "red", "green", "blue", "white", "black", "transparent")

col2hex <- function(x, alpha = FALSE) {
  args <- as.data.frame(t(col2rgb(x, alpha = alpha)))
  args <- c(args, list(names = x, maxColorValue = 255))
  do.call(rgb, args)
}

col2hex(x)
#     tomato3         red       green        blue       white       black transparent 
#   "#CD4F39"   "#FF0000"   "#00FF00"   "#0000FF"   "#FFFFFF"   "#000000"   "#FFFFFF" 
col2hex(x, alpha = TRUE)
#     tomato3         red       green        blue       white       black transparent 
# "#CD4F39FF" "#FF0000FF" "#00FF00FF" "#0000FFFF" "#FFFFFFFF" "#000000FF" "#FFFFFF00" 

For a complete mapping, you can do col2hex(colors(), alpha = TRUE).

Upvotes: 6

Related Questions