d3.schemeSpectral error when argument is 2

Hi,

New to d3 here. I was playing around with the stacked bar chart https://observablehq.com/@d3/stacked-bar-chart and I realized the schemeSpectral return ‘undefined’ if the argument passed in is 2. This means that if I want to build a bar chart with only 2 variations (say gender male and female) the color scheme will not work. Did I understand it right? What’s the work around?

Thank you

1 Like

I’m not quite sure I follow exactly how you’re trying to use d3.schemeSpectral but here’s some general information that should help.

First off, if you simply want to access a few colors to represent categorical variables, then it probably makes sense to use one of the categorical schemes as described on GitHub. For example, d3.schemeCategory10 provides a simple array of 10 easily distinguishable colors for exactly this purpose:

Note that d3.schemeSpectral, by contrast, is an example of a diverging scheme; thus, it’s best illustrated as a continuous range of colors that’s light in the middle with opposing colors diverging from the middle in opposite directions.

This type of effect is accomplished by generating an array of values and then interpolating that array. The array itself can be accessed via d3.schemeSpectral[k], where k is an integer from 3 to 9 inclusive. Note that d3.schemeSpectral[k] is undefined for k=0,1,2 because, I guess, the author wanted the index to match the length of the array and you need at least 3 colors to form a diverging scheme. I guess that’s why you found `d3.shemeSpectral[2] to be undefined.

Most often, though, the spectral colors are access via the interpolated function d3.interpolateSpectral, which is a function accepting values of t between zero and one and returning a color on that color line.

3 Likes