Basil
Basil

Reputation: 1004

Choosing most distinctive colours (hex codes) out of a pre-defined palette in R

I get given colour palettes, which is a combination of shades of the same colour (green, light green) and different colours (green, red, blue) for example. As long as the colours I use are in these palettes then its ok although they need to be as distinctive as possible. For example if I had to select 3 colours out of : green, light green, red and blue, then it should choose red, blue and one of the greens as opposed to both greens and a red. If I had a vector of hex codes as below, is there a function where R chooses the 3 most distinct colours out of the ones given. (eg the ones furthest apart from each other on the colour wheel).

colours<-c("#2ca25f" ,# dark green
"#99d8c9"  ,# light green
"#de2d26", #red
"#3182bd")#blue

Upvotes: 1

Views: 213

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

This is an interesting question; thanks for the OP.

It sounds like what you are asking is to retain the colours which maximize the difference in hue.

We can do this by converting colour strings to RGB, then RGB to HSL, then ordering the colours by hue. The differences in hue can than be ranked, and we retain only the top n colours that we wish to preserve.

The following function does all that:

color_spread <- function(colours, n) {
  
  hue_df <- data.frame(colour = colours, hue = rgb2hsv(col2rgb(colours))[1,])
  hue_df <- hue_df[order(hue_df$hue),]
  hue_df <- rbind(hue_df, hue_df[1,])
  hue_df$hue[nrow(hue_df)] <- hue_df$hue[nrow(hue_df)] + 1
  hue_df
  hue_df$diff <- c(1, diff(hue_df$hue))
  hue_df <- hue_df[order(-hue_df$diff),]
  hue_df <- hue_df[-1, ]
  hue_df$colour[seq(n)]
}

So in your example, we get:

color_spread(colours, 3)
#> [1] "#de2d26" "#2ca25f" "#3182bd"

Which are red, dark green and blue (dropping the light green)

This function will also worked on named colours:

color_spread(c('red', 'darkred', 'green', 'blue', 'dodgerblue'), 3)
#> [1] "red"        "green"      "dodgerblue"

As a side note, generating colours this way does not always produce the most harmonious or pretty plots, and does not guarantee plots that are color-blind safe.

Upvotes: 0

Related Questions