
I had a requirement to add linear and exponential trend lines to a line chart.
I found a library that provides the most important regression functions out of the box and I used it in my chart. Here the steps I followed as reference in case you have the same requirement.
The library is called regression-js and can be found here:
https://github.com/Tom-Alexander/regression-js
Thanks a lot to Tom Alexander for sharing his valuable work!
First thing I did was to add the library to my index.html:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/regression/1.3.0/regression.min.js">
This add a global regression object with the regression functions. To use them, it is enough to build a dataset array with this structure:
[knownX, dependentY]
and call the regression function you need (in my case it was just simple linear and exponential):
//Calculate regression functions
var linearRegression = regression('linear', regressionData);
regression.js will return an object containing an equation array that can be used for forecasting and an array with the calculated regression points:
//Calculate forecast
var forecast = [];
for (var j = 0; j < 100; j++) {
forecast[j] = {};
forecast[j]['linearForecast'] = [lastMillisec, lastMillisec * linearRegression.equation[0] + linearRegression.equation[1]]; //linear function
forecast[j]['exponentialForecast'] = [lastMillisec, exponentialRegression.equation[0] * Math.pow(Math.E, exponentialRegression.equation[1] * lastMillisec)];
lastMillisec += averageMillisec; //exponential function
}
Here a fiddle that shows it working:
linear and exponential regression - JSFiddle
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
25 | |
23 | |
9 | |
5 | |
5 | |
5 | |
5 | |
4 | |
4 | |
4 |