3

私はD3が初めてで、データを滑らかにするために、データの前の値と次の値の移動平均を実行しようとしています。

現在、以前の 2 つの値 + 現在の値を使用して動作しています。それは機能しますが、1) 次の値もどのように使用しますか? 2) 15 個の前の値と 15 個の次の値を使用したい場合はどうすればよいですか? (それらすべてを格納するために 30 個の個別の変数を用意するのはクレイジーです)

私は従来の JavaScript に慣れていますが、D3 でこの方法でデータをトラバースする方法についてはわかりません。誰かが私を啓発してくれることを願っています、ありがとう。

bl.ocks.org でコード全体を参照してください: http://bl.ocks.org/jcnesci/7439277

または、ここのデータ解析コードだけ:

d3.json("by_date_mod.json", function(error, data) {

// Setup each row of data by formatting the Date for X, and by converting to a number for Y.
data = data.rows;
data.forEach(function(d) {
  d.key = parseDate(String(d.key));
  d.value = +d.value;
});

x.domain(d3.extent(data, function(d) { return d.key; }));
y.domain([0, d3.max(data, function(d) { return d.value; })]);

// Setup the moving average calculation.
// Currently is a hacky way of doing it by manually storing and using the previous 3 values for averaging.
// Looking for another way to address previous values so we can make the averaging window much larger (like 15 previous values).
var prevPrevVal = 0;
var prevVal = 0;
var curVal = 0
var movingAverageLine = d3.svg.line()
.x(function(d,i) { return x(d.key); })
.y(function(d,i) {
    if (i == 0) {
        prevPrevVal  = y(d.value);
        prevVal = y(d.value);
        curVal =  y(d.value);
    } else if (i == 1) {
        prevPrevVal = prevVal;
        prevVal = curVal;
        curVal = (prevVal + y(d.value)) / 2.0;
    } else {
        prevPrevVal = prevVal;
        prevVal = curVal;
        curVal = (prevPrevVal + prevVal + y(d.value)) / 3.0;
    }
    return curVal;
})
.interpolate("basis");

// Draw the moving average version of the data, as a line.
graph1.append("path")
  .attr("class", "average")
  .attr("d", movingAverageLine(data));

// Draw the raw data as an area.
graph1.append("path")
    .datum(data)
    .attr("class", "area")
    .attr("d", area);

// Draw the X-axis of the graph.
graph1.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

// Draw the Y-axis of the graph.
graph1.append("g")
    .attr("class", "y axis")
    .call(yAxis)
  .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Value");
});
4

2 に答える 2

5

移動平均を計算する関数が必要です。

var movingWindowAvg = function (arr, step) {  // Window size = 2 * step + 1
    return arr.map(function (_, idx) { 
        var wnd = arr.slice(idx - step, idx + step + 1); 
        var result = d3.sum(wnd) / wnd.length;

        // Check for isNaN, the javascript way
        result = (result == result) ? result : _;

        return result; 
    });
};

var avgData = movingWindowAvg(avg, 7); // 15 step moving window.

完全なウィンドウを抽出できない場合、この関数は元の配列の境界で値を少しぼかすことに注意してください。

更新:結果が の場合NaN、最初に結果を現在の数値に変換します。チェックは、 Javascript で sresult == resultをテストするための推奨される方法ですNaN

于 2013-11-12T23:23:21.967 に答える