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

后端 未结 1 1994
情书的邮戳
情书的邮戳 2020-12-28 23:27

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 thi

相关标签:
1条回答
  • 2020-12-29 00:20

    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;
    }
    
    0 讨论(0)
提交回复
热议问题