Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append text to a line in d3.js

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

like image 256
Imo Avatar asked Jun 09 '16 10:06

Imo


2 Answers

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");
like image 174
Gerardo Furtado Avatar answered Nov 16 '22 19:11

Gerardo Furtado


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

like image 28
thatOneGuy Avatar answered Nov 16 '22 18:11

thatOneGuy