Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Last active November 24, 2016 05:25
Show Gist options
  • Save danielpowell4/d2608a78d81a92e6ef4bf483233a9921 to your computer and use it in GitHub Desktop.
Save danielpowell4/d2608a78d81a92e6ef4bf483233a9921 to your computer and use it in GitHub Desktop.
Linear Regression in simple structure. Accepts a data object with x + y attributes. Returns a y = mx + b style line with an r squared value. Great for D3
const linearRegression = (data, y_attr, x_attr) => {
//separate data into x and y sets
let y_data = [];
let x_data = [];
for (let i = 0; i < data.length; i++) {
y_data.push(data[i][y_attr]);
x_data.push(data[i][x_attr]);
}
// set regression variables
let lr = {};
const n = y_data.length;
let sum_x = 0;
let sum_y = 0;
let sum_xy = 0;
let sum_xx = 0;
let sum_yy = 0;
for (let i = 0; i < n; i++) {
sum_x += x_data[i];
sum_y += y_data[i];
sum_xy += (x_data[i] * y_data[i]);
sum_xx += (x_data[i] * x_data[i]);
sum_yy += (y_data[i] * y_data[i]);
}
// port variables into lr objects
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;
}
const data = [ { x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 3 } ];
console.log(linearRegression(data, 'y', 'x'));
// returns { slope: 1, intercept: 0, r2: 1 } YAY!
// adaption from script supplied in Trent Richardson's April 2010 post
@danielpowell4
Copy link
Author

danielpowell4 commented Nov 24, 2016

If you're looking for a simple solution like this, I recommend Simple Statistics

Here is a CodePen with a simple D3 v4 implementation of a Line chart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment