2013-03-08 82 views
2

我使用D3.js繪製svg行。我想通過在添加到行路徑之前移除重複(x,y)點來提高性能。在D3或javascript中完成此操作的最佳方法是什麼?我正在從json文件加載數據,用於此測試,但它可能會在服務器中的數組中出現。d3行過濾掉(刪除)複製點

請參閱下面的代碼片段和控制檯輸出。

感謝所有幫助

 var x = d3.scale.linear().domain([xMin, xMax]).rangeRound([0, width]); 
     var y = d3.scale.linear().domain([yMin, yMax]).rangeRound([height, 0]); 

     var line = d3.svg.line() 
      .x(function(d, i) { 
       var xPoint = x((i + 1) * xMult); 
       console.log("xPoint= " + xPoint.toString()); 
       return xPoint; }) 
      .y(function(d) { 
       var yPoint = y(d); 
       console.log("yPoint= " + yPoint.toString()); 
       return yPoint; }) 
      .interpolate("basis-open") 
      .tension(0); 


      ... 


     // Add the valueline path. 
     g.append("path") 
      .attr("class", "line") 
      .attr("d", line(data)); 


-------------------------------------------------- 
Console Output from two lines in code above 
console.log("xPoint= " + xPoint.toString()); 
console.log("yPoint= " + yPoint.toString()); 
---------------------------------------------- 

xPoint= 0 
yPoint= 24 
xPoint= 0 
yPoint= 24 
xPoint= 1 
yPoint= 24 
xPoint= 1 
yPoint= 24 
xPoint= 1 
yPoint= 24 
xPoint= 1 
yPoint= 24 
xPoint= 2 
yPoint= 24 
xPoint= 2 
yPoint= 25 
xPoint= 2 
yPoint= 25 
xPoint= 2 
yPoint= 24 
xPoint= 3 
yPoint= 25 
xPoint= 3 
yPoint= 25 
xPoint= 3 
yPoint= 25 
xPoint= 3 
yPoint= 25 
xPoint= 4 
yPoint= 25 

回答

0

我會用underscore _.uniq method傳遞一個自定義的迭代函數(如JS {} !== {})。

像這樣的東西(適用於你自己的上下文)

_.uniq(data, false, function(d1, d2) { 
    return (d1.x === d2.x && d1.y === d1.y); 
}); 
1

與uniq的問題是,雖然你無論在陣列中的定位的刪除重複點。對於點或點的多邊形,您只需要刪除連續的重複點。這裏是一個如何使用JavaScript來做到這一點的例子。

var point1 = { x: 0, y: 24 }; 
var point2 = { x: 1, y: 24 }; 
var point3 = { x: 2, y: 24 }; 
var point4 = { x: 2, y: 25 }; 

var points = [point1, point1, 
       point2, point2, point2, point2, 
       point3, 
       point4, point4, 
       point3]; 

var pointsAreEqual = function(point1, point2) { 
    return point1.x === point2.x && point1.y === point2.y; 
} 

var removeConsecDupes = function(items, itemsAreEqual) { 
    var previous, results = []; 

    var callback = function(value, index) { 
     if (index === 0 || !itemsAreEqual(previous, value)) { 
      results.push(value); 
     } 
     previous = value; 
    } 
    items.forEach(callback); 

    return results; 
} 

var results = removeConsecDupes(points, pointsAreEqual); 

console.dir(results); 

結果:

[ { x: 0, y: 24 }, 
    { x: 1, y: 24 }, 
    { x: 2, y: 24 }, 
    { x: 2, y: 25 }, 
    { x: 2, y: 24 } ] 
+1

感謝您的幫助,我將與數據的一些玩。但是,我真的正在尋找更多以D3.js爲中心的方法。問題是實際的線點來自比例數據d3.scale。而不是來自實際的數據。 – 2013-03-08 22:12:42