Update your chart definition by adding an empty dataset:
{
label: "Trend 1",
borderColor: 'rgba(200,0,0)',
backgroundColor: 'rgba(200,0,0)',
data: [],
fill: false,
}
Right after your chart definition (in the jsfiddle) add these lines:
arrayForRegression= []; // Declare the array which will contains calculated point of trend line
for (i=0; i < ChartVisits.data.datasets[0].data.length; i++) {
arrayForRegression.push([i, ChartVisits.data.datasets[0].data[i]]); // Fill the array with the "y" values to be approximated by regression
}
regr = regression("polynomial", arrayForRegression, 2); // Calculare polynomial regression
convertedRegressionArray = []; // Declare an array to hold the regression line in charts.js format
for (i=0; i < ChartVisits.data.datasets[0].data.length; i++) { // Fill the array with calculated values
convertedRegressionArray.push(regr.points[i][1]);
}
ChartVisits.config.data.datasets[2].data = convertedRegressionArray; // Put the regression array, converted to charts format, into chart
ChartVisits.update();
In your HTML, add this line IN BODY SECTION to include the library:
<script type="text/javascript" src="js/regression.min.js"></script>
Library from:
https://bl.ocks.org/daluu/5bb59ef3f3fed3de227535da367649ba
https://gist.github.com/daluu/5bb59ef3f3fed3de227535da367649ba
The code of the function is obfuscated/minified, anyway the call syntax is:
var linReg = regression('linear', data);
var polyReg = regression('polynomial', data, 2);
var expoReg = regression('exponential', data);
var powReg = regression('power', data);
var logReg = regression('logarithmic', data);
Data format:
var data = [[500,2.5], [1000,3], [1500,3], [2000,3.3], [3000,3.6], [4000,4], [5500,4.8], [6000,5], [7000,5], [8000,5.5], [9000,6], [12000,7], [14000,8], [15000,8], [18000,9], [20000,10], [21000,10], [24000,11], [28000,12], [30000,13], [50000,18]];
But I don't know exactly how to implement it in charts.js or any other library.
This discovery led me to look for "javascript regression.min.js" , finding many resources.
NOTE: there is an error in index.html:
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
should be:
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
NOTE2:
I think there is a major bug in linear regression part: the returned equation object (an array of coefficients) is in reversed order w.r.t polynomial format.
Examples:
3x^2+2x+1 is returned as array [1, 2, 3] , so each coefficient must be multiplied by Math.pow(x, array position):
y = equation[0] * Math.pow(x,0) + equation[1] * Math.pow(x,1) + equation[1] * Math.pow(x,1) ** correct **
2x + 1 should be returned as array [1,2] but it is returned as [2,1] --> bug?
y = equation[0] * Math.pow(x,1) + equation[1] * Math.pow(x,0)