Search code examples
typescriptchartshighchartsag-gridag-grid-angular

Rsquare best fit line in actual and precited scatter plot with d3.js/chart.js/highcharts


I wanted to draw rSquared best fit line in scatter plot of actual and predicted values , where I was given the rsquare value , I first thought of to use ag grid chart , but could not find a way , so thinking of using any of the js chart package (d3.js , chart.js , highcharts.js) is it possible to draw this rsquare line in scatter plot . for reference I added data in this plunkr , but used ag grid chart but could not find any way to do that .

  rsquared: number = 0.987;

plunkr code https://plnkr.co/edit/rhQfOrHRQGwD7TrZ?preview


Solution

  • Here you can find 2 articles that may help you on how to do it in Highcharts: https://www.highcharts.com/blog/tutorials/data-science-and-highcharts-linear-regression/ https://www.highcharts.com/blog/tutorials/calculating-and-drawing-a-linear-regression-using-highcharts/

      function (data) {
        function regression(arrWeight, arrHeight) {
          let r, sy, sx, b, a, meanX, meanY;
          r = jStat.corrcoeff(arrHeight, arrWeight);
          sy = jStat.stdev(arrWeight);
          sx = jStat.stdev(arrHeight);
          meanY = jStat(arrWeight).mean();
          meanX = jStat(arrHeight).mean();
          b = r * (sy / sx);
          a = meanY - meanX * b;
          //Set up a line
          let y1, y2, x1, x2;
          x1 = jStat.min(arrHeight);
          x2 = jStat.max(arrHeight);
          y1 = a + b * x1;
          y2 = a + b * x2;
          return {
            line: [
              [x1, y1],
              [x2, y2]
            ],
            r
          };
        }