2016-11-06 50 views
1

我有x和y座標,我應該在單個Y軸上表示(我的想法是計算兩點之間的距離並且表示爲Y軸,我也有時間,我代表X軸,我嘗試了以下內容:但是,如何使用陣列來固定Y軸刻度?是否有任何可以達到這個水平?請幫助使用數組計算座標之間的距離並設置Y軸和比例 - D3.js

d3.csv("xxx.csv", function(error, data) { 

     for (var i=0; i< data.length ; i++) 
      { 
     datax[i-2] = Math.sqrt((data[i].x1 - data[i-1].x1)* (data[i].x1 - data[i-1].x1) 
         + (data[i].y1 - data[i-1].y1)* (data[i].y1 - data[i-1].y1)); 
    datay[i] = d.Time; 
     // } 
// } 

如果我使用下面的方法,我沒有辦法訪問數組的索引元素或使用'd'。或者我如何實現使用下面的距離計算?

// load data 
d3.csv("xxx.csv", function(error, data) { 

// change string (from CSV) into number format 
    data.forEach(function(d) { 
    d.x1 = +d.x1; 
    d.y1 = +d.y1; 
console.log(d); 
}); 

實施例的數據:

類型studentId時間X1 Y1 Z1 X2 Y2 Z2 X3 Y3
PositionA 106 92 881.42 371.92 1.05 15.93 0 10.4 1
PositionA 106 92.4 893.87 459 1.05 15.84 0 6.2 1
PositionA 106 92.6 898.98 430 1.05 16.01 1.41 0 1
PositionA 106 92.8 900.1 416.94 1.05 16.6 0 356.62 1
PositionA 106 93 904.1 416.94 16.85 1.05 0 353.85 1
PositionA 106 93.2 920 416.94 1.05 16.43 0 354.27 1
位置A 106 93.4 925 416.94 1.05 16.43 0 354.27 1

+0

我已經發布了相同的參考數據 – sagar

回答

0

您可以使用引用數組中前一個對象的forEach。在這裏,我創建一個新的鍵/值相提並論,命名爲distance,從第二個對象(第一對象,當然,沒有以前的記錄來計算的距離):

data.forEach(function(d,i){ 
    if(i>0){ 
    d.distance = Math.sqrt(Math.pow((d.x1 - data[i-1].x1),2) 
     + Math.pow((d.y1 - data[i-1].y1),2)); 
    } 
}); 

這是一個演示。在本演示中,我改變了你的CSV通過d3.csv創建的對象的最終陣列(因爲我不能使用SO片段CSV文件):

var data = [{"type":"PositionA","studentId":"106","Time":"92","x1":"881.42","y1":"371.92","z1":"1.05","x2":"15.93","y2":"0","z2":"10.4","x3":"1"},{"type":"PositionA","studentId":"106","Time":"92.4","x1":"893.87","y1":"459","z1":"1.05","x2":"15.84","y2":"0","z2":"6.2","x3":"1"},{"type":"PositionA","studentId":"106","Time":"92.6","x1":"898.98","y1":"430","z1":"1.05","x2":"16.01","y2":"0","z2":"1.41","x3":"1"},{"type":"PositionA","studentId":"106","Time":"92.8","x1":"900.1","y1":"416.94","z1":"1.05","x2":"16.6","y2":"0","z2":"356.62","x3":"1"},{"type":"PositionA","studentId":"106","Time":"93","x1":"904.1","y1":"416.94","z1":"1.05","x2":"16.85","y2":"0","z2":"353.85","x3":"1"},{"type":"PositionA","studentId":"106","Time":"93.2","x1":"920","y1":"416.94","z1":"1.05","x2":"16.43","y2":"0","z2":"354.27","x3":"1"},{"type":"PositionA","studentId":"106","Time":"93.4","x1":"925","y1":"416.94","z1":"1.05","x2":"16.43","y2":"0","z2":"354.27","x3":"1"}]; 
 

 
data.forEach(function(d,i){ 
 
    if(i>0){ 
 
    d.x1 = +d.x1; 
 
    d.y1 = +d.y1; 
 
\t d.distance = Math.sqrt(Math.pow((d.x1 - data[i-1].x1),2) 
 
     +Math.pow((d.y1 - data[i-1].y1),2)); 
 
\t } 
 
}); 
 

 
console.log(data)

現在,你可以簡單地請在您的dataviz中使用您的data的屬性distance

+0

它的工作!萬分感謝 – sagar

相關問題