2016-12-15 67 views
0

試圖在這個可縮放的旭日圖形添加路徑上面的文本數據:Zoomable Sunburst 我有這樣的代碼:添加路徑,但也路徑上方的文本 - D3js v3?

d3.json(jsonUrl, function(error, data) { 
    if (error) { 
     throw error; 
    } 

    svg.selectAll("g") 
     .data(partition.nodes(data)) 
     .enter() 
     .append("g") 
     .append("path") 
     .attr("d", arc) 
     .style("fill", function(d) { 
      return color((d.children ? d : d.parent).name); 
     }) 
     .on("click", self.click) 
     .append("text") 
     .text(function(d) { 
      //console.dir(d); 
      return d.name + "\n" + formatNumber(d.value); 
     }); 
    }); 

但它不工作。沒有文字顯示。我知道這是這樣的,但我犯了錯誤。目前我正在使用D3js版本3。

有些想法?

+3

嘗試追加textPath爲「文本」元素的子元素。將.text放在textPath元素上。 –

+2

除了Robert Longson的答案被僞裝成評論之外,你必須知道哪些元素可以是父母,哪些元素可以是孩子。您**不能**將文本追加到路徑中。請點擊此處:http://stackoverflow.com/documentation/d3.js/2537/core-svg-concepts-used-in-d3-js-visualization/17339/correctly-appending-an-svg-element#t=201612151331295707414 –

+0

嘗試了.append(「text」)。append(「textPath」).text(/ *獲取路徑的文本* /),並且標籤的子標籤位於標籤內,這當然不起作用。雖然它在HTML部分的Firebug中可見,但我沒有看到文本。 – Vlad

回答

0

我剛發現這個Donut Chart的例子,並在我的代碼中改變了一些部分。 雖然看起來很雜亂,但它完成了這項工作。也許有些拋光我能得到體面的外觀:

Zoomable sunburst with text

這裏是我的代碼:

var svg = d3.select("body") 
     .append("svg") 
     .attr("width", width) 
     .attr("height", height) 
     .append("g") 
     .attr("transform", "translate(" + (width/2) + "," + (height/2) + ")"), 
g = null; 

d3.json(dataFile, function(error, data) { 
    if (error) { 
     throw error; 
    } 

    g = svg.selectAll(".arc") 
     .data(partition.nodes(data)) 
     .enter() 
     .append("g") 
     .attr("class", "arc"); 

    g.append("path") 
     .attr("d", arc) 
     .style("fill", function(d) { 
      return color((d.children ? d : d.parent).name); 
     }) 
     .on("click", self.click); 

    g.append("text") 
     .attr("transform", function (d) { 
      return "translate(" + arc.centroid(d) + ")"; 
     }) 
     .attr("dy", ".35em") 
     .text(function (d) { 
      return d.name + "\n" + formatNumber(d.value); 
     }); 
});