Zikes
Zikes

Reputation: 5886

How can I use d3.js to create a trend/exponential regression line?

I'm trying to create a curved line showing a trend in data in a graph, but I can't figure out how to generate the necessary data points, similar to the second graph in this image:

Least Squares Fitting Graphs

All of the documentation and examples I find use math that goes over my head, any pseudocode would be great.

Upvotes: 6

Views: 4795

Answers (1)

Zikes
Zikes

Reputation: 5886

I was able to plot an exponential regression line with the below code:

function square(x){return Math.pow(x,2);};

function array_sum(arr){
  var total = 0;
  arr.forEach(function(d){total+=d;});
  return total;
}

function exp_regression(Y){
  var n = Y.length;
  var X = d3.range(1,n+1);

  var sum_x = array_sum(X);
  var sum_y = array_sum(Y);
  var y_mean = array_sum(Y) / n;
  var log_y = Y.map(function(d){return Math.log(d)});
  var x_squared = X.map(function(d){return square(d)});
  var sum_x_squared = array_sum(x_squared);
  var sum_log_y = array_sum(log_y);
  var x_log_y = X.map(function(d,i){return d*log_y[i]});
  var sum_x_log_y = array_sum(x_log_y);

  a = (sum_log_y*sum_x_squared - sum_x*sum_x_log_y) /
      (n * sum_x_squared - square(sum_x));

  b = (n * sum_x_log_y - sum_x*sum_log_y) /
      (n * sum_x_squared - square(sum_x));

  var y_fit = [];
  X.forEach(function(x){
    y_fit.push(Math.exp(a)*Math.exp(b*x));
  });

  return y_fit;
}

Upvotes: 10

Related Questions