如何在 d3 图形中向边缘添加标签

How to add label to edges in d3 graph

本文关键字:边缘 添加 加标签 图形 d3      更新时间:2023-09-26

请看http://bl.ocks.org/rkirsling/5001347

它显示了一些节点以及它们之间的边缘。您能否告诉要在其中添加什么代码以及在哪里使边缘具有标签。您可以假定标签的任何合适位置,也可以假定任何标签文本。谢谢。

您可以添加标签,就像添加链接本身的路径一样。您需要做的就是根据链接连接的两个节点的位置计算位置。代码看起来像这样。

svg.selectAll("text").data(links).enter()
   .append("text")
   .attr("x", function(d) { return d.source.x + (d.target.x - d.source.x)/2; })
   .attr("y", function(d) { return d.source.y + (d.target.y - d.source.y)/2; })
   .text(function(d) { return d.something; });

请注意,在tick函数中,您还需要更新标签的位置。