Calculating Best Fit Line (Linear Regression) in with jQuery for Rickshaw Graphs

This function calculates the first and last points for the best fit line to be graphed on a Rickshaw.js chart.
We assume the points parameter is of the form [ { x: x1, y:y1}, {x:x2, y:y2}, ... ] .


function calculate_best_fit(points)
{
    // just in case
    if(points.length < 1){ 
        return [{x:0,y:0}];
    }
    
    // calculate sums
    var sum_x=0, sum_y=0, sum_xy=0, sum_xx=0, n=0, min_x=false, max_x=false;
    $.each(points, function(i, p){
            n++;
        sum_x += p.x;
        sum_y += p.y;
        sum_xy += p.x*p.y;
        sum_xx += p.x*p.x;
        min_x = (min_x === false || min_x > p.x) ? p.x : min_x;
        max_x = (max_x === false || max_x < p.x) ? p.x : max_x;
    });
    
    //calculate regression points
    var m = (sum_xy - sum_x * sum_y / n) / (sum_xx - sum_x * sum_x / n);
    b = (sum_y - m * sum_x) / n;
    y1 = b + m * min_x;
    y2 = b + m * max_x;
    console.log([ {x:min_x, y:y1}, {x:max_x, y:y2} ]);
    return [ {x:min_x, y:y1}, {x:max_x, y:y2} ];  
}




Here is the Rickshaw Graph code

    var points = [{x:1,y:3},{x:9,y:1},{x:4,y:4},{x:2,y:8}];

    var best_fit = calculate_best_fit(points);


    var chart = new Rickshaw.Graph( {

    element: document.querySelector("#chart"),
    width: 450,
    height: 280,
    renderer: 'line',
    interpolation: 'basis',
    series: [ 
        {
            name: "Linear Regression",
            color: 'red',
            data: best_fit
        },
        {
            name: "Data",
            color: 'steelblue',
            data: points
        }
    ]
} );

No comments:

Post a Comment