D3.js & Crossfilter.js: Brushing Ordinal Scales for Bars & Choropleths

ScreenShotThere are surprisingly few online examples of solving this problem with D3. There’s Mike’s original example and this one.

This problem would seem to be simple until you try to use ordinal values that are actually numeric to produce something like a distribution chart.

The reference examples for Brushing D3 Charts typically involve a handy helper library called Dimensional Charting (dc.js) that abstracts you from most of the D3 and Crossfilter details. Useful if you just need something simple but unhelpful if you need to do things it doesn’t support. In which case, you’ll find yourself extending dc.js with D3 and thinking, “I should have just learned how to do this in D3 and saved myself the time spent picking through the dc.js API docs and SO questions”.

If you get to this point (like I did) you’ll find only a few examples of SVG brushing with Crossfilters done natively in D3. And all are pretty inaccessible for new comers. They involve iterating over arrays of reusable Chart objects (very sensible) peppered with ternary operators and terse variable and function names. This original and frankly overly sophisticated pattern seems to have become the basis for all subsequent work. It all has the feel of a secret society or private members club…

So, here it is. A very simple and hopefully well documented example of native D3 SVG Brushing of Ordinal Scales to filter a Crossfilter domain and update a Choropleth. And as a bonus I’ve thrown in some real 2013 Medicare Hospital Spend Per Beneficiary (MSPB) data.

Screen Shot barChart

In the end I have to thank Couchand for taking my +50 StackOverflow reputation for his insight in how to get this working.

An important obstacle in working with ordinal scales and SVG Brushing is the lack of an .invert() method to convert pixel coordinates to your ordinal data range. I have to thank AmeliaBR for this answer which involves using ordinal.range() and ordinal.rangeBand() to calculate brush extent values.

The X axis similarly involves some hackery to filter the ordinal scales to get a sensible looking axis scales and labels.

All in all, this turned out to be a more challenging visualization project than I expected. Full source code and data files on the Github repo with technical instructions in the README.md

[gist https://gist.github.com/nyquist212/1c83356daf0bf79653e5]