2014-09-04 41 views
1

我通過工作斯科特·穆雷的exercise from Chapter 9 of his book - 具體而言,採用更新的選擇引入新的數據點。他用一個簡單的條形圖演示它,然後將標籤更新爲練習。作爲免責聲明,我幾乎是一個完整的d3 noob。d3.js:標籤是不尊重自己的位置(簡單的條形圖)

所以我設法讓標籤轉移到圖表上每個新的數據點到達。但是,由於神祕的原因,他們並沒有將自己置於每個酒吧中。古怪,老,原始數據點酒吧標籤 - 只有換新不工作。這裏是什麼樣子(新數據是從右邊滑動):

enter image description here

這裏是我的代碼:

  var labels = svg.selectAll("text") 
       .data(dataset); 


      labels.enter() 
       .append("text") 
       .text(function(d) { 
        return d; 
        }) 
       .attr("x", w) 
       .attr("y", function(d) { 
        return h - yScale(d) + 14; 
        }) 
       .attr("font-family", "sans-serif") 
       .attr("font-size", "11px") 
       .attr("fill", "white"); 


      labels.transition() 
       .duration(500) 
       .text(function(d) { 
        return d; 
       }) 
       .attr("x", function(d, i) { 
        return xScale(i) + xScale.rangeBand()/2 ; 
       }) 
       .attr("y", function(d) { 
        return h - yScale(d) + 14; 
       }); 

我的直覺是,這件事情在第三塊腳麻 - 之後labels.transition(),特別是,我的xScale.rangeBand()/2業務正在發生。但任何見解都將非常受歡迎!

回答

1

標籤被正確地放置。你應該屬性text-anchor設置爲middle得到水平居中的標籤。

labels.enter() 
     .append("text") 
     .attr("text-anchor", "middle") 
     .text(function(d) { 
      return d; 
      }) 
     .attr("x", w) 
     .attr("y", function(d) { 
      return h - yScale(d) + 14; 
      }) 
     .attr("font-family", "sans-serif") 
     .attr("font-size", "11px") 
     .attr("fill", "white"); 

快樂學習!

+0

真棒 - 工作。謝謝,巴勃羅。我錯過了原始標籤上早期的文本錨點.attr。 – 2014-09-05 04:03:24