如何在D3中添加文字?

问题描述 投票:1回答:1

这是指我之前的问题

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);
d3.js text
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.