dc.js – how to create a row chart from multiple columns

Interesting problem! It sounds somewhat similar to a pivot, requested for crossfilter here. A solution comes to mind using “fake groups” and “fake dimensions”, however there are a couple of caveats:

  • it will reflect filters on other dimensions
  • but, you will not be able to click on the rows in the chart in order to filter anything else (because what records would it select?)

The fake group constructor looks like this:

function regroup(dim, cols) {
    var _groupAll = dim.groupAll().reduce(
        function(p, v) { // add
            cols.forEach(function(c) {
                p[c] += v[c];
            });
            return p;
        },
        function(p, v) { // remove
            cols.forEach(function(c) {
                p[c] -= v[c];
            });
            return p;
        },
        function() { // init
            var p = {};
            cols.forEach(function(c) {
                p[c] = 0;
            });
            return p;
        });
    return {
        all: function() {
            // or _.pairs, anything to turn the object into an array
            return d3.map(_groupAll.value()).entries();
        }
    };
}

What it is doing is reducing all the requested rows to an object, and then turning the object into the array format dc.js expects group.all to return.

You can pass any arbitrary dimension to this constructor – it doesn’t matter what it’s indexed on because you can’t filter on these rows… but you probably want it to have its own dimension so it’s affected by all other dimension filters. Also give this constructor an array of columns you want turned into groups, and use the result as your “group”.

E.g.

var dim = ndx.dimension(function(r) { return r.a; });
var sidewaysGroup = regroup(dim, ['a', 'b', 'c', 'd']);

Full example here: https://jsfiddle.net/gordonwoodhull/j4nLt5xf/5/

(Notice how clicking on the rows in the chart results in badness, because, what is it supposed to filter?)

Leave a Comment