D3.js自定义可折叠缩进树。根据数据设置节点的位置

时间:2016-08-17 18:48:35

标签: javascript d3.js

我使用d3构建了以下图表。 enter image description here

enter image description here

以下是我使用的代码: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 image description here

...所以我一直在玩这部分代码:

// 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);

我尝试更改对角线功能的源和目标值,但似乎没有做任何事情。我错过了一些关于path.links如何与源节点和目标节点对齐的内容。我正在查看D3.js文档,但是想知道是否有人可以指出我正确的方向或注意上述代码中的任何缺陷或缺少功能。

使用D3.js第3版。

1 个答案:

答案 0 :(得分:1)

在我看来,您希望为每个节点更改应用于B的{​​{1}},而不是为transform更改<g>x 。这样,所有节点都被描述为相同(在正确位置的组偏移,并且在组内所有元素y<rect>总是缩进相同的。 但也许我误解了你的意图。