2012-11-27 97 views
6

我試圖創建表示數據以曲線趨勢的曲線,但我不能找出如何產生必要的數據點,與此類似圖像中的第二曲線圖:如何使用d3.js創建趨勢/指數迴歸線?

Least Squares Fitting Graphs

我發現所有的文檔和例子都使用數學,任何僞代碼都會很好。

回答

10

我能夠繪製與下面的代碼指數迴歸線:

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

如果有可能再次檢查我的工作任何的數學家,這將是大加讚賞。謝謝。 – Zikes

+2

http://bl.ocks.org/zikes/raw/4279121/謝謝Zikes!是否有可能獲得趨勢線表達式? – aloplop85