2015-04-01 48 views
2

我是使用d3庫的新手,我試圖讓傳說之間有相等的空間。在我的工作的現階段 - 不提供平等的空間。d3中的傳說之間的等距空間

我想知道我該如何修復。

enter image description here

下面是代碼,我到目前爲止有:

var margin = { top: 20, right: 50, bottom: 30, left: 60 }; 

    self.drawLegends = function() { 

      var legendData = [{ "color": "blue", text: "Normal Distribution" }, { color: "green", text: " Ave A" }, { color: "red", text: "Ave B" }] 
      var legends = self.svg.selectAll("g legends").data(legendData); 
      var legendBox = legends.enter() 
       .append("g") 
       .attr("transform", function (d, i) { return "translate(" + parseFloat((i + 1) * (($("#chart").width() - margin.left - margin.right)/4)) + ",-10)" }) 

     var circles = legendBox.append("circle") 
      .attr("r", 5) 
      .attr("stroke", "black") 
      .attr("fill", function (d, i) { return d.color }) 

     legendBox.append("text") 
      .attr("dx", function (d) { return 10 }) 
      .attr("dy", function (d) { return 5 }) 
      .attr("fill","white") 
      .text(function (d) { return d.text }) 
    }, 
+0

只是爲了檢查:彩色圓圈是偶數間隔,你的意思是圓的位置應由文本的長度決定的?如果是這樣,你可以在文本上使用'.getComputedTextLength()'。這裏有一個小提琴,我做了它顯示你的問題 - 這是創建這些工作很有用:http://jsfiddle.net/henbox/7Le4tc92/1/ – 2015-04-01 18:01:51

回答

4

這裏有一個更新的擺弄着什麼,我認爲你是後:http://jsfiddle.net/henbox/7Le4tc92/2/

當你第一次繪製circle並且text在每個g元素中,請勿使用變換。然後,選擇每個g並獲得文字長度(使用getComputedTextLength())來計算你想要的翻譯:

svg.selectAll("g") 
    .attr("transform", function (d, i) { 
     var x_pos = d3.select(this).select("text").node().getComputedTextLength() + 20; 
     x_offset = x_offset + x_pos; 
      return "translate(" + (x_offset - x_pos + margin.left) + ", 20)" 
    }) 
+0

好的答案.... – Mark 2015-04-01 18:39:39

+0

感謝亨利,這是偉大的答案! – casillas 2015-04-01 20:31:06