Search code examples
javascriptaveragedygraphs

Show average of dygraph points, which dynamically amends as the user zooms


I have seen this - Horizontal line to show average in dygraph - and it doesn't quite answer my question.

I have the following simple dygraph:

g2 = new Dygraph(
  document.getElementById("graphdiv2"),
  "../newDataFile.csv",
  { ... }
);

where newDataFile.csv has two columns.

What I would like to show is the average of the points plotted (as a line or just a number), and for this average to change as I zoom in to different parts of the graph. Any ideas?


Solution

  • var idx=1; //change this value if you have several plots.
    var data = g2.rawData_;
    var sum = data.map(function(e){return e[idx]})
                  .reduce(function(a,b){return a+b});
    var average = sum/data.length;
    

    If you want to keep only values displayed if the graph is zoomed :

    var idx=1; //change this value if you have several plots.
    var data = g2.rawData_.slice(g2.boundaryIds_[idx][0],g2.boundaryIds_[idx][1]+1);
    var sum = data.map(function(e){return e[idx]})
                  .reduce(function(a,b){return a+b});
    var average = sum/data.length;