D3 - 添加文本标签以更新力布局图

时间:2016-12-05 17:30:21

标签: javascript d3.js svg

我一直在努力扩展迈克博斯托克的D3示例之一,我在网上看到了一些成功。

https://bl.ocks.org/mbostock/1095795

我设法让这个符合我的需要,我可以添加额外的节点和链接。我正在尝试为每个节点添加标签,我想我缺少一些基本的东西。

我为文本标签添加了一个新组,并将其包含在示例中的restart函数和模拟的tick函数中。从我的角度来看,DOM中出现的内容似乎是正确的,但标签只出现在图的中间。

这是我所得到的小提琴,任何帮助都会非常感激。我一般都没有很多D3 / SVG的经验,所以我认为我必须缺少一些非常基础的东西。

特别是我添加的是:

为文字添加其他组

var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"),
link = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".link"),
node = g.append("g").attr("stroke", "#fff").attr("stroke-width", 1.5).selectAll(".node"),
text = g.append("g").selectAll("text"); 

根据节点ID

更新文本组
  // Apply the general update pattern to the text.
  text = text.data(nodes, function(d) { return d.id; });
  text.exit().remove();
  text = text.enter().append("text").text(function (d) {return d.id;}).merge(text);

在tick函数中更新以匹配节点

  text.attr("cx", function(d) { return d.x;})
  .attr("cy", function(d) { return d.y;});

https://jsfiddle.net/3b68rm94/1/

非常感谢。

1 个答案:

答案 0 :(得分:3)

使用

text.attr("x", function(d) { return d.x;})
  .attr("y", function(d) { return d.y;});

cx和cy用于圈子(https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/cx)。 x和y似乎有效。