Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
francesco_alborghetti
Active Participant

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

3 Comments
Labels in this area