1
votes

I have the following data:

Store   year    earnings
A   2011    1000
A   2012    2000
A   2013    2000
A   2014    3000
B   2012    200
B   2012    300
B   2012    500
B   2014    3000
B   2015    4000
C   2013    2000
C   2013    200
C   2015    1200
C   2016    4000

What I would like to do is to use dc.js to get cumulative sum per store and per year and display it in a series chart.

The cumulative sum per store per year would be

Store   year    earnings
    A   2011    1000
    A   2012    3000
    A   2013    5000
    A   2014    8000
    B   2012    1000
    B   2014    4000
    B   2015    8000
    C   2013    2200
    C   2015    3400
    C   2016    7400

I have searched around and saw that this can be done for a simple dimension and group like so:

function createCumulativeGroup(source_group) {
        return {
            all:function () {
                var cumulate = 0;
                return source_group.all().map(function(d) {
                    cumulate += d.value;

                    return {key:d.key, value:cumulate};
                });
            }
        };
    }

But in order to use a series chart, I need to reduce by both year and store, putting both into a composite key. And when I try to use the above function with a series chart, the accumulation happens across all stores, resulting in much larger values than expected.

How can I do a cumulative sum that works with a series chart?

1
please check the jsfiddle below: jsfiddle.net/thyfoubq/10Thanos
"It doesn't work" is never a good description of the problem. :) I've edited this to make clear it's about extending cumulative sums to work with the series chart. Please verify this is what you meant.Gordon
Hi Gordon, you are right, the correct would be it doesn't work with series chart. Thanks!Thanos

1 Answers

2
votes

Your createCumulativeGroup function just accumulates all values across stores. You need to make it accumulate values by store. This should work:

function createCumulativeGroup(source_group) {
        return {
            all:function () {
                var cumulate = {};
                return source_group.all().map(function(d) {
                  if(cumulate[d.key[0]]) {
                    cumulate[d.key[0]] += d.value;
                  } else {
                    cumulate[d.key[0]] = d.value;
                  }
                  return {key:d.key, value:cumulate[d.key[0]]};
                });
            }
        };
    }

https://jsfiddle.net/rn3ja9n4/