这是我使用的代码:https://jsfiddle.net/eb2L618g/1/
我在使用 D3.js API 时遇到问题,尤其是如何根据动态数据设置每个节点的 x 位置。特别是,当我更改节点的 x 位置时,连接源节点和目标节点的 path.links 没有正确更新并且不再接触源节点和目标节点。首先,我偏移节点 x 位置:
我在更新函数中添加了这个:
// Enter any new nodes at the parent's previous position.
nodeEnter.append("rect")
.attr("y", -barHeight / 2)
// added this function to try to offset the x position
.attr("x", function(d){
return d.x +20 // hardcode offset for now
})
.attr("height", barHeight)
.attr("width", barWidth)
.style("fill", color)
.on("click", click);
上面的添加从它的父节点的 x 位置偏移了每个节点,到目前为止还不错但是它打破了其中文本的对齐方式,所以我添加了这个:
nodeEnter.append("text")
.attr("x", function(d){
return d.x +20
})
.attr("dy", 3.5)
.attr("dx", 5.5)
.text(function(d) { return d.name; });
但现在 path.links 没有对齐:
...所以我一直在研究这部分代码:
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
.transition()
.duration(duration)
.attr("d", diagonal);
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
我试过更改对 Angular 线函数的源值和目标值,但似乎没有任何作用。我遗漏了一些关于 path.links 如何与其源节点和目标节点对齐的信息。我正在查看 D3.js 文档,但想看看是否有人可以指出正确的方向或注意到上述代码中的任何缺陷或缺失的功能。
使用 D3.js 版本 3。
最佳答案
在我看来你想要更改 transform
适用于 <g>
对于每个节点,而不是 x
和 y
对于 <rect>
.这样所有节点都被描述为相同的(在正确位置的组偏移量,并且在组内所有元素 rect
和 text
总是缩进相同。
但也许我误解了你的意图。
关于javascript - D3.js 自定义可折叠缩进树。根据数据设置节点位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004181/