在d3.js中绘制滚动/移动平均值 [英] Plot rolling/moving average in d3.js
问题描述
寻找一种方法来绘制d3中的滚动/移动平均值,而无需事先处理数据.因此,我想通过平均每个数据点和其后的两个点来平滑该行.我的代码是这样的
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));
我可以指定movingAverageLine来计算以下数据点的平均值吗?我想不出在该函数中访问它们的方法.
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.
我已经在jsfiddle上建立了一个示例. http://jsfiddle.net/tjjjohnson/XXFrg/2/#run >
I have set up an example on jsfiddle. http://jsfiddle.net/tjjjohnson/XXFrg/2/#run
推荐答案
先前的解决方案会导致累积移动平均值.
A previous solution results in a cumulative moving average.
我修改了d3.svg.line()
:
I modified the fiddle made by John O'Connor to provide an n-moving average by passing a custom interpolation function to d3.svg.line()
:
movingAvg = function(n) {
return function (points) {
points = points.map(function(each, index, array) {
var to = index + n - 1;
var subSeq, sum;
if (to < points.length) {
subSeq = array.slice(index, to + 1);
sum = subSeq.reduce(function(a,b) {
return [a[0] + b[0], a[1] + b[1]];
});
return sum.map(function(each) { return each / n; });
}
return undefined;
});
points = points.filter(function(each) { return typeof each !== 'undefined' })
// Note that one could re-interpolate the points
// to form a basis curve (I think...)
return points.join("L");
}
}
var movingAverageLine = d3.svg.line()
.x(function(d,i) { return x(i); })
.y(function(d,i) { return y(d); })
.interpolate(movingAvg(6));
这篇关于在d3.js中绘制滚动/移动平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!