Plotting averages with dc.js / crossfilter

78 views Asked by At

I have some data like this

[
    {type:"a", series:[0.1, 0.2, 0.2, 0.1, -0.1]},
    {type:"b", series:[0.3, 0.4, 0.5, 0.6, 0.7]},
]

There is a dimension for type, then I'm doing a group and averaging out each series per type.

Is there a nice way to plot the averaged series per type? Obviously I want it to update with any new filters.

I tried flattening out my data as

[
    {type:"a", index:0, value:0.1},
    {type:"a", index:1, value:0.2},
    ...
]

and making index a dimension as well. But it's getting a bit slow when I add more data; I never filter the index dimension, so adding it to crossfilter is just an extra cost; and finally it messes up the counts for each type.

1

There are 1 answers

2
marcel On BEST ANSWER

Try this:

var group = typeDimension.group().reduce(reduceAdd, reduceRemove, reduceInitial);

function reduceAdd(p, v) {
    ++p.count
    p.sum += calculateAverage(v['series']);
    p.avg = p.sum / p.count;
    return p;
}

function reduceRemove(p, v) {
    --p.count
    p.sum -= calculateAverage(v['series']);
    p.avg = p.sum / p.count;
    return p;
}

function reduceInitial() {
    return {count: 0, sum: 0, avg: 0};
}

function calculateAverage(numbers) {
    var sum = 0;
    number.forEach(function(num) {
        sum += num;
    });
    return sum / numbers.length;
}