2013-05-13 150 views
3

我有一些數據,我試圖用D3強制佈局顯示。道歉如果這是一個天真的問題,或者如果我在問題標題中使用的術語不準確。我無法看到我正在尋找的答案。D3 Force佈局 - 子圖聚類功能

我做了一個小提琴與樣品展示我在這裏大概什麼:

http://jsfiddle.net/stevendwood/f3GJT/8/

enter image description here

在這個例子中我有一個節點(0),其中有很多鏈接。另一個節點(16)的鏈接數量較少,0和16都連接到15.

所以我想爲0和16是小羣集與他們的連接節點出現在他們周圍一個很好的圓。

我徒然試圖根據鏈接的數量來定製費用,但我認爲我想要做的是以某種方式使節點更多地吸引到它們連接的節點,並且更少地吸引到它們未連接的節點。

我想是這樣的,如果可能的:

enter image description here

var w = 500, 
h = 500, 
nodes = [], 
links = []; 

/* Fake up some data */ 
for (var i=0; i<20; i++) { 
    nodes.push({ 
     name: ""+i 
    }); 
} 

for (i=0; i<16; i++) { 
    links.push({ 
     source: nodes[i], 
     target: nodes[0] 
    }); 
} 

links.push({ 
    source: nodes[16], 
    target: nodes[15] 
}); 

for (i=17; i<20; i++) { 

    links.push({ 
     source: nodes[i], 
     target: nodes[16] 
    }); 
} 

var countLinks = function(n) { 
    var count = 0; 
    links.forEach(function(l) { 
     if (l.source === n || l.target === n) { 
      count++; 
     } 
    }); 

    return count; 
} 

///////////////////////////////////////////// 

var vis = d3.select("body").append("svg:svg") 
    .attr("width", w) 
    .attr("height", h); 

var force = d3.layout.force() 
    .nodes(nodes) 
    .links([]) 
    .gravity(0.05) 
    .charge(function(d) { 
     return countLinks(d) * -50;  
    }) 
    .linkDistance(300) 
    .size([w, h]); 


var link = vis.selectAll(".link") 
     .data(links) 
     .enter().append("line") 
     .attr("class", "link") 
     .attr("stroke", "#CCC") 
     .attr("fill", "none"); 

var node = vis.selectAll("circle.node") 
    .data(nodes) 
    .enter().append("g") 
    .attr("class", "node") 
    .call(force.drag); 

node.append("svg:circle") 
    .attr("cx", function(d) { return d.x; }) 
    .attr("cy", function(d) { return d.y; }) 
    .attr("r", 14) 
    .style("fill", "#CCC") 
    .style("stroke", "#AAA") 
    .style("stroke-width", 1.5) 

node.append("text").text(function(d) { return d.name; }) 
    .attr("x", -6) 
    .attr("y", 6); 

force.on("tick", function(e) { 
    node.attr("transform", function(d, i) { 
     return "translate(" + d.x + "," + d.y + ")"; 
    }); 

    link.attr("x1", function(d) { return d.source.x; }) 
     .attr("y1", function(d) { return d.source.y; }) 
     .attr("x2", function(d) { return d.target.x; }) 
     .attr("y2", function(d) { return d.target.y; }) 
}); 

force.start(); 
+0

你真的不能與沒有自定義修改的力佈局實現這一目標。我建議查看其他佈局,或者,如果您知道自己需要什麼,只需靜態指定佈局即可。 – 2013-05-13 17:51:03

回答

4

聲明力量佈局時,你爲什麼離開了鏈接?如果你在後面添加這些,它看起來更接近你想要的東西:

var force = d3.layout.force() 
    .nodes(nodes) 
    //.links([]) 
    .links(links) 
    .gravity(0.1) 
    .charge(-400) 
    .linkDistance(75) 
    .size([w, h]); 

http://jsfiddle.net/f3GJT/11/

enter image description here

+0

啊 - 非常感謝你! – Woody 2013-05-14 11:25:03