Plot rolling/moving average in d3.js

Viewed 8947

Looking for a way to plot rolling/moving average in d3 without having to manipulate the data in advance. So I want to smooth out the line by averaging each data point with the two after it. My code is like this

var data = [3, 66, 2, 76, 5, 20, 1, 3, 8, 90, 2, 5, 70];

var w = 20,
    h = 80;

var x = d3.scale.linear()
    .domain([0, 1])
    .range([0, w]);
var y = d3.scale.linear()
    .domain([0, 100])
    .rangeRound([h, 0]);

var chart = d3.select("body").append("svg")
    .attr("class", "chart")
    .attr("width", w * data.length -1)
    .attr("height", h);

var line = d3.svg.line()
    .x(function(d,i) { return x(i); })
    .y(function(d) { return y(d); })


var movingAverageLine = d3.svg.line()
    .x(function(d,i) { return x(i); })
    .y(function(d) { return y(d); })

chart.append("svg:path").attr("d", line(data));
chart.append("svg:path").attr("d", movingAverageLine(data));

Can I specify movingAverageLine to calculate the average of the following data points? I can't think of a way to access them in that function.

I have set up an example on jsfiddle. http://jsfiddle.net/tjjjohnson/XXFrg/2/#run

3 Answers
Related