2016-06-09 71 views
0

我試圖將文本追加到條形圖上創建的一行上。問題是我可以看到文本元素被創建。但它並沒有顯示在svg的任何地方。代碼 一部分,我追加文本如何將文本追加到d3.js中的一行

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

+1

你不能文本追加到一條線,你需要將其追加到兩個容器 – thatOneGuy

回答

6

您不能text追加到line。只是爲文字創建另一個變量:

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"); 
3

我以前見過這個,但似乎無法找到它。基本上你需要同時爲線和文本的容器,所以當你翻譯該行的文本與它的動作:

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') 

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

相關問題