2013-02-18 157 views
2

我已經在d3中搜索了很多以進行可視化。我能夠從數據庫中可視化我的數據。現在,我想要改變不同d3節點之間的距離。有一個函數force.linkdistance()用於指定節點之間的距離。目前我提供了100的恆定距離。我想根據數據庫中的列來改變每個鏈接的距離。這是一個數字列。我也附加我的代碼。請幫助,如果有的話。
如何在有效佈局中改變d3節點之間的距離

var okCounter=0; 
var width = 960, 
height = 500; 

console.log("still ok here:",okCounter++); 

var svg = d3.select("body").append("svg") 
    .attr("width", width) 
    .attr("height", height); 
console.log("still ok here:",okCounter++); 
var force = d3.layout.force() 
    .gravity(.05) 
    .distance(100) 
    .charge(-100) 
    .size([width, height]); 
console.log("still ok here:",okCounter++); 
d3.json("getdata.php", function(error,json) { 
    force 
     .nodes(json.nodes) 
     .links(json.links) 
     .start(); 
console.log("still ok here:",okCounter++); 
    var link = svg.selectAll(".link") 
     .data(json.links) 
     .enter().append("path") 
     .attr("class", "link"); 
console.log("still ok here:",okCounter++); 
    var node = svg.selectAll(".node") 
     .data(json.nodes) 
    .enter().append("g") 
     .attr("class", "node") 
    // .call(force.drag); 
console.log("still ok here:",okCounter++); 
    node.append("image") 
     .attr("xlink:href", "http://www.clker.com/cliparts/5/6/3 /a/1194984675331456830utente_singolo_architett_01.svg.med.png") 
     .attr("x", -8) 
     .attr("y", -8) 
     .attr("width", 24) 
     .attr("height", 24); 
console.log("still ok here:",okCounter++); 
    node.append("text") 
     .attr("dx", 24) 
     .attr("dy", ".35em") 
     .text(function(d) { return d.name }); 
console.log("still ok here:",okCounter++); 
    force.on("tick", function() { 
    link.attr("d", function(d) { 
var dx = d.target.x - d.source.x, 
    dy = d.target.y - d.source.y, 
    dr = Math.sqrt(dx * dx + dy * dy); 
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " +  d.target.x + "," + d.target.y; 
}); 
console.log("still ok here:",okCounter++); 
    node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); 
}); 
});</script> 

回答

4

如果你想force.linkDistance變化,使用的功能,而不是一個常量。

如果距離是一個常數,那麼所有的鏈接都是相同的距離。否則,如果距離是一個函數,則函數針對每個鏈接(按順序)進行評估,通過鏈接及其索引並將this上下文作爲強制佈局;然後函數的返回值用於設置每個鏈接的距離。只要佈局開始,該功能就會被評估。

(從https://github.com/d3/d3-3.x-api-reference/blob/master/Force-Layout.md#linkDistance

您可能還希望與傳遞函數force.linkStrength實驗,雖然我懷疑的效果將是微妙的(還沒有嘗試過我自己)。

1
var force = d3.layout.force() 
    .linkDistance(function(d) { 
      return(/* whatever computation you want the distance of each link to be */); 
    } 
    .start(); 
相關問題