I am sharing linFit function that estimates best linear regression for data (x, y)
Arguments for this function are as follows:
- x: array of x values
- y: array of y values
The function returns an array of 2 elements [m, b], where
- m: slope of the linear regression
- b: intercept of the linear regression
To use it in your custom charts, just copy the function at the end of the script and call it from your code as below:
p = linFit(x, y);
Then you can calculate estimated y (ye) for a given x (xk) as:
ye = p[1] * xk + p[2];
Chart RRa1 shows one implementation of this function (with some modification for that specific purpose).
I hope it is useful for developing more and more awesome charts.
Code for the linFit function:
function linFit(x, y) {
let SXi2 = 0;
let SXi = 0;
let SXiYi = 0;
let SYi = 0;
let n = x.length;
for (let i = 0; i < n; i++) {
SXi = SXi + x[i];
SXi2 = SXi2 + x[i] * x[i];
SYi = SYi + y[i];
SXiYi = SXiYi + x[i] * y[i];
}
let det_A = SXi2 * n - SXi * SXi;
let m = 0;
let b = y[0];
if (det_A != 0) {
m = (SXiYi * n - SXi * SYi) / det_A;
b = (SXi2 * SYi - SXiYi * SXi) / det_A;
}
return [m, b];
}