Bar Chart on Dimension-1 and Stacked by Dimension-2

倾然丶 夕夏残阳落幕 提交于 2019-12-06 10:30:21
Gordon

I mentioned this in my answer to your other question, but why not expand on it a little bit here.

In the dc.js FAQ there is a standard pattern for custom reductions to reduce more than one value at once.

Say that you have a field named type which determines which type of value is in the row, and the value is in a field named value (in your case these are cat and quantity). Then

var group = dimension.group().reduce(
    function(p, v) { // add
        p[v.type] = (p[v.type] || 0) + v.value;
        return p;
    },
    function(p, v) { // remove
        p[v.type] -= v.value;
        return p;
    },
    function() { // initial
        return {};
    });

will reduce all the rows for each bin to an object where the keys are the types and the values are the sum of values with that type.

The way this works is that when crossfilter encounters a new key, it first uses the "initial" function to produce a new value. Here that value is an empty object.

Then for each row it encounters which falls into the bin labelled with that key, it calls the "add" function. p is the previous value of the bin, and v is the current row. Since we started with a blank object, we have to make sure we initialize each value; (p[v.type] || 0) will make sure that we start from 0 instead of undefined, because undefined + 1 is NaN and we hate NaNs.

We don't have to be as careful in the "remove" function, because the only way a row will be removed from a bin is if it was once added to it, so there must be a number in p[v.type].

Now that each bin contains an object with all the reduced values, the stack mixin has helpful extra parameters for .group() and .stack() which allow us to specify the name of the group/stack, and the accessor.

For example, if we want to pull items a and b from the objects for our stacks, we can use:

.group(group, 'a', kv => kv.value.a)
.stack(group, 'b', kv => kv.value.b)

It's not as convenient as it could be, but you can use these techniques to add stacks to a chart programmatically (see source).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!