如何在D3中在线添加文本?

时间:2019-03-20 04:34:11

标签: d3.js text

这是我的上一个问题

How to set the direction of the arrowhead?

我正在尝试使用以下输入在箭头上添加文本

x1,y1,x2,y2,Flag,text
1,2,3,2,L,AA
3,3,5,3,R,BB 
5,3,6,3,L,CC 
7,5,7,5,R,DD
8,6,8,6,L,EE 
9,7,2,7,L,FF

我找到了下面的代码,但不确定如何使用它在每个箭头上添加文本吗?

var myText =  svg.append("text")
   .attr("y", height - 10)//magic number here
   .attr("x", function(){ return x(lineEnd)})
   .attr('text-anchor', 'middle')
   .attr("class", "myLabel")
   .text(d.text);

1 个答案:

答案 0 :(得分:1)

只需添加行即可添加文本。

示例:

svg.selectAll(null)
      .data(data)
      .enter()
      .append("text")
      .attr("x", d => (d.x1+d.x2)/2) //I am putting the text on the middle of x and y length of th eline. But you may change it as per your need.
      .attr("y", d => (d.y1+d.y2)/2)
      .attr("font-size", "10")
      .text((d)=>d.text)

下面的工作代码:

const csv = `x1,y1,x2,y2,flag,text
    1,2,3,2,L,AA
    3,3,5,4,R,BB
    5,3,6,3,L,CC
    7,5,8,5,R,DD
    8,6,9,6,L,EE
    9,7,2,8,L,FF`;

    const data = d3.csvParse(csv, function(d) {
      d.x1 = +d.x1 * 20;
      d.y1 = +d.y1 * 15;
      d.x2 = +d.x2 * 20;
      d.y2 = +d.y2 * 15;
      
      return d;
    });

    data.forEach(function(d) {
      if ((d.flag === "L" && d.x1 < d.x2) || (d.flag === "R" && d.x1 > d.x2)) d.x1 = d.x2 + (d.x2 = d.x1, 0);
    });

    const svg = d3.select("svg");

    const marker = svg.append("defs")
      .append("marker")
      .attr("id", "marker")
      .attr("viewBox", "0 0 10 10")
      .attr("refX", "5")
      .attr("refY", "5")
      .attr("markerWidth", "6")
      .attr("markerHeight", "6")
      .attr("orient", "auto")
      .append("path")
      .attr("d", "M 0 0 L 10 5 L 0 10 z");

    const enterSelection = svg.selectAll(null)
      .data(data)
      .enter()
      .append("line")
      .attr("x1", d => d.x1)
      .attr("y1", d => d.y1)
      .attr("x2", d => d.x2)
      .attr("y2", d => d.y2)
      .attr("marker-end", "url(#marker)")
      .style("stroke-width", "1px")
      .style("stroke", "black");

svg.selectAll(null)
      .data(data)
      .enter()
      .append("text")
      .attr("x", d => (d.x1+d.x2)/2)
      .attr("y", d => (d.y1+d.y2)/2)
      .attr("font-size", "10")
      .text((d)=>d.text)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
    <svg></svg>