如何在力向图d3中向边缘添加文本?

时间:2019-08-21 22:55:01

标签: d3.js

我希望能够在节点之间的边缘两侧添加文本。但是,我无法在节点顶部显示文本的方式似乎无法将文本添加到边缘。我该怎么办?我应该尝试其他方法吗?

关于这个问题,我已经广泛研究了其他线程,但是我似乎无法理解为什么我的代码无法正常工作/让他们的代码可以在我的图表上工作。我是d3和Javascript的初学者,所以也许我忽略了一些简单的东西。

可以在以下位置找到我的代码的链接:https://jsfiddle.net/obe02/zxva4f5r/

  // update existing links
  path.classed("selected", (d) => d === selectedLink)
      .style("marker-start", function(d) {return getMarkers(d, false, true)})
      .style("marker-end", function(d) {return getMarkers(d, false, false)});

  // remove old links
  path.exit().remove();

  // add new links
  path = path.enter().append("svg:path")
    .attr("class", "link")
    .classed("selected", (d) => d === selectedLink)
    .style("marker-start", function(d) {return getMarkers(d, false, true)})
    .style("marker-end", function(d) {return getMarkers(d, false, false)})
    .on("mousedown", (d) => {
      if (d3.event.shiftKey) return;

      // select link
      mousedownLink = d;
      selectedLink = (mousedownLink === selectedLink) ? null : mousedownLink;
      selectedNode = null;
      update();
    })
    .merge(path);

path.append("svg:text")
    //.attr("dx", function(d) { return d.w/10})
    //.attr("dy", -4)
    .attr("x", function(d) {return d.length / 2})
    .attr("y", function(d) {return (d.length / 2) + 2})
    .attr("class", "edgelabel")
    .text((d) => d.length);```

1 个答案:

答案 0 :(得分:0)

我在这里找到了感兴趣的人的答案。这并不像我最初想象的那么简单。您必须创建一些不同的元素才能显示文本。

Add text/label onto links in D3 force directed graph