2013-12-20 134 views
0

我是D3的新手,我有我的圆环图,但是我无法在每个圆弧外面得到圆弧标签。D3饼图(圆环图)每个圆弧外面的图表标签

我想在紫色http://bl.ocks.org/Guerino1/2295263中得到类似紫色的标签,但我无法让它在我的圆环图上工作。

我正在使用下面的代码来追加每个弧的标签,但它看起来像arc.centroid不按预期方式工作。

 var arcs = vis.selectAll("g.slice") 
    arcs.append("svg:text") 
     .attr("transform", function(d, i) { //set the label's origin to the center of the arc 
     d.outerRadius = svgOuterRadius + 40; // Set Outer Coordinate 
     d.innerRadius = svgOuterRadius + 35; // Set Inner Coordinate 
     return "translate(" + arc.centroid(d) + ")"; 
     }) 
     .attr("text-anchor", "middle") //center the text on it's origin 
     .style("fill", "Purple") 
     .style("font", "bold 14px Arial") 
     .text(function(d, i) { return 'label'+i; }); //get the label from our original 

Here是我的jsfiddle:

我真的很感激它提前。

回答

1

基本问题是,您的弧段path已翻译,并且在添加标签时不考虑该翻译。如果您查看已链接的示例,则会看到path分段没有任何翻译就被添加,这意味着可以添加text元素而没有附加偏移量。

要解决简单地偏移到:

arcs.append("svg:text") 
     .attr("transform", function(d, i) { //set the label's origin to the center of the arc 
      var c = arc.centroid(d); 
     return "translate(" + (svgWidth/2 + c[0]) + "," + (svgHeight/2 + c[1]) + ")"; 
}) 
// etc 

完整的示例here

+0

非常感谢你,它看起来不错。我能再问你一件事吗?我希望每个标签都在每个弧的外面,但是添加d.outerRadius = <我的外半径> + 50; d.innerRadius = <我的外半径> + 45;在arc.centroid(d)之前没有帮助。你知道我怎样才能让每个弧线以外的每个标签位置? – user2975436

+0

[此问题](http://stackoverflow.com/questions/8053424/label-outside-arc-pie-chart-d3-js)应该有所帮助。 –

+0

http://stackoverflow.com/a/12543354/2031033另一个好主意 –