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:
All of the documentation and examples I find use math that goes over my head, any pseudocode would be great.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With