我制作了一个饼图d3 js,我想为每条路径添加标签。
我写了一些代码:
var labels = svg.selectAll('path').insert("text").data(pie(data))
.text( function (d) { return d.value; })
.attr("font-family", "sans-serif")
.attr('x', 0)
.attr('y', 0)
.attr("font-size", "12px")
.attr("fill", "red");
Run Code Online (Sandbox Code Playgroud)
但是没有可见的结果,只有我可以看到 Chrome 开发人员工具中有新的文本元素。

我需要如何更改代码以查看饼图部分上的所有标签?
您不能将text节点附加为path. 您应该使用gtag 将这些元素分组,并将paths 和texts附加为g元素的子元素。
// append "g" it is a container for your slice and label
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
.append("g")
.attr("class", "slice");
// draw slice of pie chart
arcs.append("path")
.attr("fill", function(d, i){
return color(i);
})
.attr("d", function (d) {
return arc(d);
});
// draw label
arcs.append("text")
.attr("transform", function(d){
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text( function(d, i) {
return data[i].label;}
);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您的结构将如下所示:
<g>
<path d=...></path>
<text>some text</text>
</g>
<g>
<path d=...></path>
<text>some text</text>
</g>
...
Run Code Online (Sandbox Code Playgroud)
检查工作示例:
// append "g" it is a container for your slice and label
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
.append("g")
.attr("class", "slice");
// draw slice of pie chart
arcs.append("path")
.attr("fill", function(d, i){
return color(i);
})
.attr("d", function (d) {
return arc(d);
});
// draw label
arcs.append("text")
.attr("transform", function(d){
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text( function(d, i) {
return data[i].label;}
);
Run Code Online (Sandbox Code Playgroud)
<g>
<path d=...></path>
<text>some text</text>
</g>
<g>
<path d=...></path>
<text>some text</text>
</g>
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2307 次 |
| 最近记录: |