# Playing with CIE Lab Colors in R

Currently I’m taking the wonderful course Computing for Data Analysis on Coursera, and in this weeks lecture I learned about how to define custom color palettes in R.

You can do this using the `colorRampPalette()` function that comes with the grDevices package. Calling this function will return another function that you can call to generate the color palette.

```> library(grDevices)
> palette = colorRampPalette(c("red", "yellow"))
> palette(5)
[1] "#FF0000" "#FF3F00" "#FF7F00" "#FFBF00" "#FFFF00"```

By default, R uses the RGB color space to interpolate between colors. As I mentioned in earlier posts, this is not as ideal choice for data visualization. Fortunately, R allows you to interpolate in CIE Lab color space. Let’s write a quick function `plotColors()` to plot the colors. The function takes two arguments: palette is the palette function returned by colorRampPalette and n defines the number of color steps we want to display. Internally the function simply draws a bar chart without axes and with no spacing between the bars.

```plotColors = function(palette, n=10) {
colors = palette(n)
barplot(rep(1,n), col=colors, border=colors, space=0, yaxt='n')
}```

Now let’s look at the default interpolation between red and yellow in five steps. On my screen the first two colors look almost the same, although they are equally-spaced in RGB.

```> pal = colorRampPalette(c("red", "yellow"))
> plotColors(pal, 5)```

You can set the color space to CIE Lab by setting the parameter space to “Lab”. As you can see, the difference is huge. That’s not a question of taste.

```> pal = colorRampPalette(c("red", "yellow"), space="Lab")
> plotColors(pal, 5)```

Feel free to play around with that code snippets yourself. Instead of the named colors you can also create palettes between arbitrary colors by providing hexadecimal codes:

```> pal = colorRampPalette(c("#FF0000", "#0000FF"), space="Lab")
> plotColors(pal, 5)```

You can find the full code for this example on Github.

## 1 Comment →Playing with CIE Lab Colors in R

1. Pap Tamas

Thanks for the post. My question is if using Lab space, will it work for all color combinations for example: blue to yellow? Or it is possible that some colors will be out of the gamut?