9๐
โ
I typically use the regression package.
First, add the package as an external script.
Second, clean your data. Just basic checks here:
const clean_data = datoa
.filter(({ x, y }) => {
return (
typeof x === typeof y && // filter out one string & one number
!isNaN(x) && // filter out `NaN`
!isNaN(y) &&
Math.abs(x) !== Infinity &&
Math.abs(y) !== Infinity
);
})
.map(({ x, y }) => {
return [x, y]; // we need a list of [[x1, y1], [x2, y2], ...]
});
Then run
const my_regression = regression.linear(
clean_data
);
The result will be something like:
{
'points': [[4,3.79],[4.75,3.83],[5.5,3.87],.....],
'equation': [0.05,3.59],
'r2': 0.26,
'string': 'y = 0.05x + 3.59'
}
Done. Weโve got our [x,y] points. So transform the linear regression points into something that chartjs can render:
const useful_points = my_regression.points.map(([x, y]) => {
return y;
// or {x, y}, depending on whether you just want y-coords for a 'linear' plot
// or x&y for a 'scatterplot'
})
You can add these points either as
- another line chart dataset
- or with an annotation plugin.
Source:stackexchange.com