我是 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
这是我的 JSfiddle:
我真的很感激提前。
基本问题是您的弧形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
完整示例在这里。