避免D3.js中的子节点重叠 [英] Avoid overlapping of child nodes in D3.js
问题描述
我正在使用D3.js构建一个显示Facebook用户及其Facebook朋友的树形结构.根是用户,子节点是朋友.我的UI宽度固定,问题是子节点会相互重叠.
I am building a tree structure showing the Facebook user and his/her Facebook friends using D3.js. The root is the user and the child nodes are the friends. I have a fixed width in my UI and the problem is the child nodes will overlap to each other.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
nodes.forEach(function(d) { d.y = d.depth * 130; });
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("value", function(d){
return d.id; })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; });
var defs = node.append("defs").attr("id", "imgdefs");
var imgPattern = defs.append("pattern")
.attr("id", "img")
.attr("height", 50)
.attr("width", 50)
.attr("x", "0")
.attr("y", "0");
imgPattern.append("image")
.attr("height", 60)
.attr("width", 60)
.attr("xlink:href", function(d) { return d.img; });
nodeEnter.append("circle")
.attr("r", 30)
.style("stroke","white")
.style("stroke-width", 4)
.attr("fill", "url(#img)");
我想为子节点每行/深度显示10个朋友.任何帮助或建议,请.谢谢!
I would like to display 10 friends per row/depth for the child nodes. Any help or suggestions please. Thank you!
这是我的jsfiddle:在此处编码
Here is my jsfiddle: CODE HERE
推荐答案
一种方法是设置separation
属性/d3/wiki/Tree-Layout"rel =" nofollow noreferrer>树状布局.这是代码段:
One way to accomplish this is to set the nodeSize
and separation
properties of the tree layout. Here is the snippet:
var tree = d3.layout.tree()
//.size([height, width])
.nodeSize([30,])
.separation(function separation(a, b) {
return a.parent == b.parent ? 2 : 1;
});
我将nodeSize
属性的x
尺寸设置为等于圆的半径.
I set the x
dimension of the nodeSize
property equal to the radius of the circles.
此外,必须更改g
转换以重新定位图表:
Also, a change in the g
transform is necessary to reposition the chart:
.attr("transform", "translate(" + (margin.left + width/2) + "," + margin.top + ")");
You can safely ignore the size
property (see documentation in the link above and this SO answer).
这是一个 FIDDLE .我添加了另一排不同深度的圆圈,以检查该解决方案是否足够可靠.我认为这应该可以帮助您.
Here is a FIDDLE with the changes. I added another row of circles at a different depth to check whether the solution was robust enough. I think this should get you going.
这篇关于避免D3.js中的子节点重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!