Skip to content Skip to sidebar Skip to footer

D3.js Moving Average With Previous And Next Data Values

I'm new to D3 and trying to do a moving average of previous and next values on my data in order to smooth it out. Currently, I have it working using the 2 previous values + the cur

Solution 1:

You need a function to calculate the moving average:

var movingWindowAvg = function (arr, step) {  // Window size = 2 * step + 1return 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.

Note that this functions fudges the values a bit at the borders of the original array, when a complete window cannot be extracted.

Update: If the result is NaN, convert the result to the present number in the beginning. Checking result == result is the recommended way of testing for NaNs in Javascript.

Solution 2:

If you really don't need a variable size window, this cumulative average might be a faster option without the slicing overhead:

functioncumAvg(objects, accessor) {
      return objects.reduce(
          function(avgs, currObj, i) { 
            if (i == 1) {
              return [ accessor(currObj) ];
            } else {
              var lastAvg = avgs[i - 2]; // reduce idxs are 1-based, arrays are 0
              avgs.push( lastAvg + ( (accessor(currObj) - lastAvg) / i) );
              return avgs;
            }
          }
    }

Post a Comment for "D3.js Moving Average With Previous And Next Data Values"