Color sorting is an interesting problem

color palette for #336699

I love exploring colors, color theory, and color spaces. I have made several color sorting and selecting tools, including a color palettes page.

One of the challenges I encountered is that I want to show a color palette derived from a base color. Since every proper color palette should be sorted by hue, and I am not hand-picking these colors, I need to sort the resultant color set programmatically. The problem is that my current hue-sorting function doesn’t sort related colors the way I expect. You can see the sorting on this page. Notice how there’s a nice long line of perfectly-sorted greens, and then the one oddball green at the end? What’s up with Lime anyway?

I know where I went wrong. I copied the color-sorting code from elsewhere on the internet. The code, which can be seen here, does a two-fold sorting process. First it clusters colors together in a first pass, and then sorts them again on a second pass, by determining the distance between colors.

There are always outliers. The outliers are colors that are not close to anything else in my dataset, so they don’t get sorted with the rest. I haven’t figured out how to address these outliers in a visually pleasing way. The code is also so baroque that I have a hard time getting into it the weeds of it.

I have written my own color-distance functions which do simple arithmetic on the original R, G, and B values. This code can be seen here. The function limits the R, G, B values to a short numerical range. It works–it produced the palette shown above–but I am not sure if it can be scaled to a generic color-sorting function. It feels a bit hokey.

I also found this which seems to do the job, but it uses jQuery. I could rewrite it in vanilla JavaScript if I find that it gets the job done.

One of my goals is to have a perfectly fast, library-free page that puts together visually pleasing sets of color on the fly. I think it’s possible.

Let me know your thoughts on color sorting, colors, or code.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s