Home › Forums › Chart Support › Average line on line chart › Reply To: Average line on line chart
You can calculate simple moving average(SMA) by writing few lines of code and pushing the respective values to dataSeries will render the chart with SMA series. Please take a look at the below code snippet for calculating 7 Day SMA and pushing it to chart dataSeries.
function calculateMovingAverage(chart) {
var numOfDays = 7;
// return if there are insufficient dataPoints
if(chart.options.data[0].dataPoints.length <= numOfDays) return;
else {
// Add a new line series for Moving Averages
chart.options.data.push({
type: "spline",
markerSize: 0,
name: "SMA",
yValueFormatString: "#,##0.00",
dataPoints: []
});
var total;
for(var i = numOfDays; i < chart.options.data[0].dataPoints.length; i++) {
total = 0;
for(var j = (i - numOfDays); j < i; j++) {
total += chart.options.data[0].dataPoints[j].y;
}
chart.options.data[1].dataPoints.push({
x: chart.options.data[0].dataPoints[i].x,
y: total / numOfDays
});
}
}
}
Also, Please have a look at this JSFiddle for complete code.
___
Suyash Singh
Team CanvasJS