D3.js linear regression

Viewed 12066

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, but unfortunately I wasn't able to make them work properly:
simple-statistics.js and this one: regression.js
With regression.js I was able to get the m and b values for the line, so I could use y = m*x + b to plot the line that followed the linear regression of my graph, but couldn't apply those values to the line generator, the code I tried is the following:

d3.csv("typeStatsTom.csv", function (error, dataset) {
//Here I plot other stuff, setup the x & y scale correctly etc. 
//Then to plot the line:

        var data = [x.domain(), y.domain()];
        var result = regression('linear', data);
        console.log(result)
        console.log(result.equation[0]);
        var linereg = d3.svg.line()
                        .x(function (d) { return x(d.Ascendenti); })
                        .y(function (d) { return y((result.equation[0] * d.Ascendenti) + result.equation[1]); });
        var reglinepath = svg.append("path")
                            .attr("class", "line")
                            .attr("d", linereg(dataset))
                            .attr("fill", "none")
                            .attr("stroke", "#386cb0")
                            .attr("stroke-width", 1 + "px");

The values of result are the following in the console:

    Object
      equation: Array[2]
        0: 1.8909425770308126
        1: 0.042557422969139225
      length: 2
      __proto__: Array[0]
      points: Array[2]
      string: "y = 1.89x + 0.04"
      __proto__: Object

From what I can tell in the console I should have set up the x and y values correctly, but of course the path in the resulting svg is not shown (but drawn), so I don't know what to do anymore.
Any help is really really appreciated, even a solution involving the simple.statistics.js library would be helpful!
Thanks!

2 Answers
Related