How to draw a linear regression line in Chart.js

与世无争的帅哥 提交于 2020-03-12 05:31:07

问题


I saw other libraries support this but there is very little data for Chart.js. Can anybody indicate me the way to start with a regression line for my graph? This is my code so far:

var datiedu3 = {"labels": ['ok'],
          "datasets": [{label: 'EEE',
                        data: datoa ,

                        backgroundColor: 'rgb(255, 99, 132)',
                        borderWidth: 1,
                        showLine: false}] 
           };

function grafo2(dati, opzioni) {
  var grafoline = document.getElementById('Chartline').getContext('2d');
  new Chart(grafoline, {type: 'scatter',data: dati, options: opzioni});
};
// display the data used in dataset[0]:
console.log(datiedu3.datasets[0].data)
grafo2(datiedu3)

I figured I had to create another dataset with a line graph, and put my equation there, but I don't know how to do it and I'm a bit lost.

My whole code is here codepen


回答1:


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.


来源:https://stackoverflow.com/questions/60622195/how-to-draw-a-linear-regression-line-in-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!