-->

how to roll up dc stacked-bar example into single

2019-07-26 01:58发布

问题:

"http://dc-js.github.io/dc.js/examples/stacked-bar.html" I want to roll this kind of dataset into a single bar stacked-bar chart. I changed the

 speedSumGroup       = runDimension.group().reduce(function(p, v) {
                    p[v.Expt] = (p[v.Expt] || 0) + v.Speed;
                    return p;
                }, function(p, v) {
                    p[v.Expt] = (p[v.Expt] || 0) - v.Speed;
                    return p;
                }, function() {
                    return {};
                });

to speedSumGroup2 = runDimension.groupAll().reduce(function(p, v) {

and inspecting the group shows the data rolled up to the single expected.

Object {1: 18180, 2: 17120, 3: 16900, 4: 16410, 5: 16630}

However I inspect the data with .value() whereas the original needs an all(), and this group does not work with the chart

chart
                .width(768)
                .height(480)
                .x(d3.scale.linear().domain([1,21]))
                .margins({left: 50, top: 20, right: 10, bottom: 20})
                .brushOn(false)
                .clipPadding(10)
                .title(function(d) {
                    return d.key + '[' + this.layer + ']: ' + d.value[this.layer];
                })
                .yAxisLabel("This is the Y Axis!")
                .dimension(runDimension)
                .group(speedSumGroup2, "1", sel_stack('1'))
                .renderLabel(true);

giving "a.group.all is not a function" error. Is the result of a dimension.groupAll() a standard group that can be plugged into the chart?

回答1:

Good question - it's never been clear what kind of object a groupAll is.

As you've surmised, dc.js charts expect a "regular" group, not a groupAll. Here's a conversion function you could use:

function regularize_groupAll(groupAll) {
    return {
        all: function() {
            return [{key: 'all', value: groupAll.value()}];
        }
    };
}

Use it like this:

var speedSumReg2 = regularize_groupAll(speedSumGroup2);
...
chart
    .group(speedSumReg2, "1", sel_stack('1'))
    .stack(speedSumReg2, "2", sel_stack('2'))
...


标签: d3.js dc.js