plotly/graphing-library-docs

simple fit trace / linear regression example provided

cgfoed opened this issue · 4 comments

I just want to provide my simple code for plotting a linear fit into a scatter.
A feature that was requested for some time in plotly JS (plotly/plotly.js#4921), maybe you can just add this code into your example collection, so people will be able to find this solution and modified it to their needs:

function linearRegression(x,y){
        var lr = {};
        var n = y.length;
        var sum_x = 0;
        var sum_y = 0;
        var sum_xy = 0;
        var sum_xx = 0;
        var sum_yy = 0;

        for (var i = 0; i < y.length; i++) {

            sum_x += x[i];
            sum_y += y[i];
            sum_xy += (x[i]*y[i]);
            sum_xx += (x[i]*x[i]);
            sum_yy += (y[i]*y[i]);
        } 

        lr['sl'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);
        lr['off'] = (sum_y - lr.sl * sum_x)/n;
        lr['r2'] = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2);

        return lr;
}

var trace = {
      x: [9.87, 9.69, 9.14, 9.71, 9.19, 9.5, 9.85, 9.52, 9.34, 9.42, 9.71, 9.53, 9.13, 9.05, 9.3, 9.81, 9.32, 9.8, 9.5, 10, 9.47, 9.19, 9, 9.94, 9.4, 9.18, 9.06, 9.39, 9.59, 9.26, 9.15],
      y: [9.93, 9.85, 9.34, 9.69, 9.13, 9.4, 9.75, 9.5, 9.23, 9.45, 9.95, 9.68, 9.17, 9.2, 9.1, 10.01, 9.17, 9.99, 9.29, 10.04, 9.56, 9.2, 9.06, 9.77, 9.61, 9.09, 9.2, 9.18, 9.72, 9.1, 9.27],
      name: "Scatter",
      "marker": {"size": 5},
      "mode": "markers",
    "type": "scatter" };  
var lr = linearRegression(trace.x, trace.y);
var fit_from = Math.min(...trace.x)
var fit_to = Math.max(...trace.x)
var fit = {
  x: [fit_from, fit_to],
  y: [fit_from*lr.sl+lr.off, fit_to*lr.sl+lr.off],
  mode: 'lines',
  type: 'scatter',
  name: "R2=".concat((Math.round(lr.r2 * 10000) / 10000).toString())
};

var data = [ trace, fit ];
Plotly.newPlot('myDiv', data);

image

jxu commented

shouldn't linear regression calculations be handled by an appropriate statistical library

The above example can be done using layout.shapes too.

Is there a way that we can have the error bar from this linear regression line? I am trying to make the error bar similar to this plot https://indrajeetpatil.github.io/ggstatsplot/articles/web_only/ggscatterstats.html but in JS