Search code examples
d3.jsgraphcumulative-line-chart

d3: Plot as a cumulative graph


Does d3 have a built in method to plot a data set as a cumulative graph?

For example, if the y values are: [2, 4, 2, 2], I want them to actually be plotted as: [2, 6, 8, 10]. Does d3 have a way to do this or would I have to traverse the data set and do this manually?


Solution

  • You can check https://github.com/mbostock/d3/wiki/Arrays for more info but I think you can use the reduce() function here.

    i.e:

    [0, 2, 4, 2, 2].reduce(function(previousValue, currentValue, currentIndex, array) {
      console.log(previousValue + currentValue);//2,6,8,10
      return previousValue + currentValue;
    });