如何在 Chart.js 中绘制线性回归线

Ann*_*nna 6 javascript chart.js

我看到其他库支持这一点,但 Chart.js 的数据很少。有人可以告诉我如何从图表的回归线开始吗?到目前为止,这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

我想我必须创建另一个带有折线图的数据集,并将我的方程放在那里,但我不知道该怎么做,我有点迷失了。

我的全部代码在这里codepen

Joe*_*ook 9

我通常使用回归包

首先,将添加为外部脚本。其次,清理数据。这里只是基本检查:

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], ...]
    });
Run Code Online (Sandbox Code Playgroud)

然后运行

const my_regression = regression.linear(
  clean_data
);
Run Code Online (Sandbox Code Playgroud)

结果将类似于:

{
  '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'
}
Run Code Online (Sandbox Code Playgroud)

完毕。我们已经得到了 [x,y] 点。因此,将线性回归点转换为 Chartjs 可以呈现的内容:

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'
})
Run Code Online (Sandbox Code Playgroud)

您可以将这些点添加为