$(function() {
lineFit = function(points){
sI = slopeAndIntercept(points);
if (sI){
var N = points.length;
var rV = [];
rV.push([points[0][0], sI.slope * points[0][0] + sI.intercept]);
rV.push([points[N-1][0], sI.slope * points[N-1][0] + sI.intercept]);
return rV;
}
return [];
}
slopeAndIntercept = function(points){
var rV = {},
N = points.length,
sumX = 0,
sumY = 0,
sumXx = 0,
sumYy = 0,
sumXy = 0;
if (N < 2){
return rV;
}
for (var i = 0; i < N; i++){
var x = points[i][0],
y = points[i][1];
sumX += x;
sumY += y;
sumXx += (x*x);
sumYy += (y*y);
sumXy += (x*y);
}
rV['slope'] = ((N * sumXy) - (sumX * sumY)) / (N * sumXx - (sumX*sumX));
rV['intercept'] = (sumY - rV['slope'] * sumX) / N;
rV['rSquared'] = Math.abs((rV['slope'] * (sumXy - (sumX * sumY) / N)) / (sumYy - ((sumY * sumY) / N)));
return rV;
}
var d1 = [];
for (var i = 0; i < 14; i += 0.5) {
d1.push([i, i**2]);
}
d2 = lineFit(d1);
console.log(d2);
var plot = $.plot("#placeholder", [{
data: d1,
points: {
show: true
},
lines: {
show: true
}
},
{
data: d2,
lines:{
show: true
}
}
], {
grid: {
hoverable: true,
clickable: true
},
//series: {
trendline: {
show:true,
lineWidth:2,
fill:true,
fillColor:false,
steps:true
}
//}
}
);
});
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="1.11.0" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.js"></script>
<script data-require="[email protected]" data-semver="0.8.2" src="//cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div id="placeholder" style="width:400px; height: 400px;"></div>
</body>
</html>