How to sort HEX colors in R

To sort colors by hue in R, we need to convert the colors from HEX (hexadecimal) to RGB (red-green-blue), compute the hue values and then sort them.

Example

The I Want Hue website provides a really nice tool to get a list of colors. And it has an option to sort the colors by hue values. However, if we copy two lists of colors, how can we sort the concatenated list?

hex_a = c("#d52400", "#ffa888", "#ffb46b", "#d8c93a", "#5d6319", "#72df21",
          "#328100", "#b9cbbb", "#01ca42", "#00b773", "#01bdce", "#13d8fc",
          "#91ceec", "#2b6294", "#0269f4", "#285cb1", "#5b3de8", "#d0bef0",
          "#873fa3", "#e162ff", "#ff55ea", "#ab2080", "#f3009e", "#ff99c6",
          "#ff60a6", "#ff7f97", "#a23b49")

hex_b = c("#a33f1a", "#ffa465", "#e7c352", "#60620d", "#849300", "#88da67",
          "#008e25", "#019f50", "#b5cbc5", "#01b495", "#85d4cd", "#007681",
          "#82d1ea", "#029bcd", "#72a7ff", "#0055f0", "#5254b3", "#63568f",
          "#cc7eff", "#d000c8", "#fdabf3", "#ff63d8", "#a1317d", "#98406d",
          "#c00059", "#ffa3a9", "#ff414a")

hex = c(hex_a, hex_b)
> hex[1:6]
[1] "#d52400" "#ffa888" "#ffb46b" "#d8c93a" "#5d6319" "#72df21"
barplot(rep(1, length(hex)), col = hex, axes = F)

From HEX to RGB colors

This is how we can apply the col2rgb function from base R (already used in my post about the conversion between HEX and RGB colors) on a vector of colors:

rgb = sapply(hex, function(x){col2rgb(x)})
> rgb[,1:6]
     #d52400 #ffa888 #ffb46b #d8c93a #5d6319 #72df21
[1,]     213     255     255     216      93     114
[2,]      36     168     180     201      99     223
[3,]       0     136     107      58      25      33

The first row corresponds to red values, the second one to green values and the last one to blue values.

From RGB colors to hue values

This is how we can apply a custom function (that comes from my post about the conversion between RGB and HSL colors) on a vector of colors:

from_rgb_to_hue = function(rgb){
  R = rgb[1] / 255
  G = rgb[2] / 255
  B = rgb[3] / 255
  
  M = max(c(R, G, B))
  m = min(c(R, G, B))
  C = M - m
  
  if (C == 0){
    H = 0
    
  } else {
    if (M == R){
      H = ((G - B) / C) %% 6
      
    } else if (M == G){
      H = ((B - R) / C) + 2
      
    } else if (M == B){
      H = ((R - G) / C) + 4
    }
  }
  
  return(H * 60)
}

hue = apply(rgb, 2, function(x){from_rgb_to_hue(x)})
> hue[1:6]
 #d52400  #ffa888  #ffb46b  #d8c93a  #5d6319  #72df21 
10.14085 16.13445 29.59459 54.30380 64.86486 94.42105 

Sort hue values

barplot(rep(1, length(hex)), col = hex[order(hue)], axes = F)

Conclusion

To sum up, we can sort HEX colors by hue in R by converting them from HEX to RGB and then by computing the hue values. Is this blog post helpful to you?

Related posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply