D3.js linear regression

前端 未结 2 831
失恋的感觉
失恋的感觉 2020-12-29 13:35

I searched for some help on building linear regression and found some examples here:
nonlinear regression function
and also some js libraries that should cover this

相关标签:
2条回答
  • 2020-12-29 14:10

    I made it work using the following code found here:

       function linearRegression(y,x){
    
            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['slope'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);
            lr['intercept'] = (sum_y - lr.slope * 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 yval = dataset.map(function (d) { return parseFloat(d.xHeight); });
    var xval = dataset.map(function (d) { return parseFloat(d.Ascendenti); });
    
    
    var lr = linearRegression(yval,xval);
    // now you have:
    // lr.slope
    // lr.intercept
    // lr.r2
    console.log(lr);
    

    And then plotting a line with:

    var max = d3.max(dataset, function (d) { return d.OvershootingSuperiore; });
    var myLine = svg.append("svg:line")
                .attr("x1", x(0))
                .attr("y1", y(lr.intercept))
                .attr("x2", x(max))
                .attr("y2", y( (max * lr.slope) + lr.intercept ))
                .style("stroke", "black");
    

    Using the code I found here

    0 讨论(0)
  • 2020-12-29 14:16

    It looks to me like your path is getting drawn, just way off the screen.

    path element in firebug

    Perhaps the regression is calculated incorrectly? The problem may be on line 202:

    var data = [x.domain(), y.domain()];
    var result = regression('linear', data);
    

    If the raw data looks like [[1, 500], [2, 300]] this will find the linear regression of [[1, 2], [300, 500] which probably isn't what you want.

    I'm guessing what you'd like to do is compute the regression with the entire set of data points rather than with the graph's bounds. Then rather than charting this line for every data value, you want to just plot the endpoints.

    0 讨论(0)
提交回复
热议问题