Image may be NSFW.
Clik here to view.
So recently I’ve been working with the D3.js framework to create pie charts, bar graphs, and line graphs. The best description of D3 comes directly from their website :
“D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.”
It’s a very powerful framework that allows you to make various types of data driven illustrations to represent the underlying data very quickly. It does have a bit of a learning curve, but there are so many examples on the site, that you can usually find an example that is 50% to 90% of what you’re looking to do. With an example that is close to what you’re looking to do, it’s pretty easy to get past the learning curve.
As you can see in the attached image, I was able to create a line graph and needed to create a “trend line” or a “linear regression” line. Looking around on the internet, I found a great article by Trent Richardson that spells out the linear regression formula in javascript here: http://trentrichardson.com/2010/04/06/compute-linear-regressions-in-javascript/
Here’s the linear regression function:
function linearRegression(y,x){
var lr = {};
var n = y.length;
var sum_x = 0;
var sum_y = 0;
var sum_xy = 0;
var sum_xx = 0;
var sum_yy = 0;
for (var i = 0; i < y.length; i++) {
sum_x += x[i];
sum_y += y[i];
sum_xy += (x[i]*y[i]);
sum_xx += (x[i]*x[i]);
sum_yy += (y[i]*y[i]);
}
lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);
lr['intercept'] = (sum_y - lr.slope * sum_x)/n;
lr['r2'] = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2);
return lr;
}
Then to make the actual call, you send in the 2 arrays of data points:
var known_y = [1, 2, 3, 4];
var known_x = [5.2, 5.7, 5.0, 4.2];
var lr = linearRregression(known_y, known_x);
// now you have:
// lr.slope
// lr.intercept
// lr.r2
With the use of this function, I was able to create the trend line/ linear regression line in D3 as shown in the image above. I’ll go into more detail as how I tied it into my D3 graph in another post. Thank you Trent Richardson!
The post How to get a trend line for a javascript graph – Linear Regression appeared first on Local Wisdom.