How to append text to a line in d3.js

2019-06-04 03:48发布

I am trying to append a text to a line created on bar chart. The problem is that I can see that the text element is created. But it does not show anywhere on the svg. part of code where I append text

 var line = svg.append("line")
              .attr("x1", function(){ return x(lineEnd)})
              .attr("x2", function(){ return x(lineEnd)})
              .attr("y1", 0)
              .attr("y2", height)
              .attr("stroke-width", 6)
              .attr("stroke", "black")
              .attr("stroke-dasharray", "8,8")



  line.append('text')
             .attr('class', 'barsEndlineText')
             .attr('text-anchor', 'middle')
              .attr("x", 0)
             .attr("y", ".35em")
             .text('I am label')

see plunker for full code

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-04 04:09

I have seen this before but cant seem to find it. Basically you need a container for both the line and text so when you translate the line the text moves with it :

var line = svg.append("g")

line.append("line")
              .attr("x1", function(){ return x(lineEnd)})
              .attr("x2", function(){ return x(lineEnd)})
              .attr("y1", 0)
              .attr("y2", height)
              .attr("stroke-width", 6)
              .attr("stroke", "black")
              .attr("stroke-dasharray", "8,8")



line.append('text')
             .attr('class', 'barsEndlineText')
             .attr('text-anchor', 'middle')
              .attr("x", 0)
             .attr("y", ".35em")
             .text('I am label')

Updated PLNKR : http://plnkr.co/edit/lASjq4ysrYGqWUGtMgRd?p=preview

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-04 04:12

You can't append a text to a line. Just create another variable for the text:

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")//easy to style with CSS
   .text("I'm a label");
查看更多
登录 后发表回答