现在我正试图分离我的矩形节点,因为它们重叠,如下图所示:
我看了一下,发现 D3 提供了一个 nodeSize和 separation方法,但由于某种原因它不起作用。
我找到了这个 blog post谈论这个问题,但他说
The size property doesn’t exist in nodes, so it will be whatever property you want to control the size of them.
但显然有一个 nodeSize 方法,所以我觉得我只是错误地使用了该方法和/或博客文章已过时。我想将我的节点塑造成矩形的大小,并将它们均匀地隔开,这样它们就不会相互重叠。有谁知道如何正确使用这些方法?关于这些方法的文档没有很好的解释,也没有产生任何区别。我也找不到很多关于人们更改树的节点大小或矩形对象需要分离的示例(有一些关于圆形对象的示例,但我觉得这太不同了......)
这是相关代码。我将尝试准备一个 JSFiddle。
var margin = {top: 20, right: 120, bottom: 20, left: 120},
height = 960 - margin.right - margin.left,
width = 800 - margin.top - margin.bottom,
rectW = 70;
rectH = 30;
//bbox = NaN,
maxTextLength = 0;
var i = 0,
duration = 750,
root;
//paths from each node drawn initially here
//changed to d.x, d.y
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.x+rectW/2, d.y+rectH/2];
//.projection(function(d) { return [d.x+bbox.getBBox().width/2, d.y+bbox.getBBox().height/2];
});
var tree = d3.layout.tree()
.nodeSize([30,70])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2); })
.size([width, height]);
var svg = d3.select("body")
.append("svg")
.attr("height","100%").attr("width","100%")
.call(d3.behavior.zoom().on("zoom", redraw))
.append("g")
.attr("transform", "translate(" + margin.top + "," + margin.left + ")");
最佳答案
更新 05/04/2018:据我所知,d3 已经发生了很大变化(变得更好),变得更加模块化。对于那些正在寻找这个答案的人来说,这是使用更旧版本的 d3(特别是 v3)。
许多发现仍然与 d3-hierarchy
有关包裹在cluster.size()
and cluster.nodeSize()
下我打算潜在地更新我的示例以使用它。不过,为了历史引用,我没有触及底部。
这是一个 jsFiddle:http://jsfiddle.net/augburto/YMa2y/
编辑:更新示例并将其移至 Codepen。该示例仍然存在于 jsFiddle 上,但 Codepen 似乎有一个更好的编辑器并允许您轻松地 fork 。一旦我减少了其中的内容量,我也会尝试将示例直接添加到此答案中。
http://codepen.io/augbog/pen/LEXZKK
更新这个答案。我和我的 friend 谈过,我们查看了 size
和 nodeSize
tree.size = function(x) {
if (!arguments.length) return nodeSize ? null : size;
nodeSize = (size = x) == null;
return tree;
};
tree.nodeSize = function(x) {
if (!arguments.length) return nodeSize ? size : null;
nodeSize = (size = x) != null;
return tree;
};
当您为树设置大小
时,您设置的是固定大小,因此树必须符合该宽度和高度。当您设置 nodeSize
时,树必须是动态的,因此它会重置树的大小。
当我在 nodeSize
之后指定 size
时,我几乎覆盖了我想要的内容哈哈...
底线:如果您希望 nodeSize
起作用,您不能有固定的树大小。它将大小设置为 null
。如果要声明 nodeSize
,请不要声明 size
。
编辑:D3.js 实际上是 updated the documentation .感谢这样做的人,因为它现在更清晰了!
The nodeSize property is exclusive with tree.size; setting tree.nodeSize sets tree.size to null.
这就是我的树现在的样子。我还添加了缩放功能以及如何使文本在矩形内居中。
关于javascript - 使用 NodeSize 节点之间的 D3 树布局分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17558649/