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

标签 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);

我试过更改对 Angular 线函数的源值和目标值,但似乎没有任何作用。我遗漏了一些关于 path.links 如何与其源节点和目标节点对齐的信息。我正在查看 D3.js 文档,但想看看是否有人可以指出正确的方向或注意到上述代码中的任何缺陷或缺失的功能。

使用 D3.js 版本 3。

最佳答案

在我看来你想要更改 transform适用于 <g>对于每个节点,而不是 xy对于 <rect> .这样所有节点都被描述为相同的(在正确位置的组偏移量,并且在组内所有元素 recttext 总是缩进相同。 但也许我误解了你的意图。

关于javascript - D3.js 自定义可折叠缩进树。根据数据设置节点位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004181/

相关文章:

javascript - 如何终止捕获

Javascript - 寻找 prependTo 的替代方法,这样它就不会添加多个项目

javascript - 这种 JSON 结构是否适用于使用 d3.js 的堆叠条形图?

javascript - 使用函数索引数组

javascript - 如何仅在选择某个下拉菜单项时激活输入字段

javascript - 挖掘 JavaScript 对象的路径

javascript - 在 javascript dom 中,在 querySelector() 中转义字符

javascript - d3.json() 回调中的代码未执行

javascript - 函数不识别变量

javascript - 天/小时热图 + mySQL