我一直致力于扩展我在网上看到的 Mike Bostock 的 D3 示例之一,并取得了一些成功。
https://bl.ocks.org/mbostock/1095795
我已经设法让它满足我的需要,我可以附加额外的节点和链接。我正在尝试向每个节点添加标签,但我认为我错过了一些基本的东西。
我添加了一个新的文本标签组,并将其包含在示例的重新启动函数和模拟的刻度函数中。从我的 Angular 来看,DOM 中显示的内容似乎是正确的,但标签仅出现在图的中间。
这是我所拥有的 fiddle ,任何帮助将不胜感激。一般来说,我对 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);
更新勾选函数以匹配节点
text.attr("cx", function(d) { return d.x;})
.attr("cy", function(d) { return d.y;});
https://jsfiddle.net/3b68rm94/1/
非常感谢。
最佳答案
使用
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 似乎有效。
关于javascript - D3 - 添加文本标签以更新力布局图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979981/