Tuesday, April 23, 2013

Category Colors in R

I thought I'd write down the color palette I use for categories. I've seen many discussions about gradient color choices, but category colors are less often discussed. I have a function given below which generates colors where there is not meant to be an ordering to the color. It is important when data points are near, that they are easy to distinguish with the eye. It makes more sense to see it:


Here's the function:

# Provides contrasting colors. Light.levels is the number of lightness
# levels to use before restarting.
category.colors <- function(n, contrast=90, light.levels=3) {
shades <- c()
color.levels = 16
if(n > light.levels * color.levels) {
#recycle function
return(c(category.colors(light.levels * color.levels),
category.colors(n - light.levels * color.levels)))
}
hues <- function(n) {
sapply(0:(n-1),
function(x)
{90 *(x %% 4) + 22.5 * floor(x / 4)})
}
while(n > color.levels) {
#recylce with lightness
shades <- c(shades,
hcl(h=hues(n),
l=(100 - (80 / light.levels) *
floor(n / color.levels)),
c=contrast ))
n <- n - color.levels
}
if(n > 0) {
shades <- c(shades,
hcl(h=hues(n),
c=contrast, l=70 ))
}
return(shades)
}
view raw gistfile1.r hosted with ❤ by GitHub

Here's a comparison of the function (top) and the built-in rainbow function (bottom) which serves the same purpose.



1 comment:

  1. Thank you so much for sharing!!!! I was looking for some palette which I could use with categories in a line plot! This palette is beautiful and useful. Thank you!

    ReplyDelete