简体   繁体   English

如何正确地向d3饼图添加标签?

[英]How to correctly add labels to the d3 pie chart?

I made a pie chart using d3 js and I want to add labels to the every path. 我使用d3 js制作了一个饼图,我想在每个路径中添加标签。

I wrote some code: 我写了一些代码:

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");

but there is no visible result, only I can see that there are new text elements in the Chrome developer tools. 但没有可见的结果,只有我能看到Chrome开发人员工具中有新的文本元素。

结果和Chrome开发工具

How I need to change my code to see all labels on the pieces of my pie chart? 我如何更改代码以查看饼图上的所有标签?

You cannot append text node as a child for path . 您不能将text节点附加为path的子节点。 You should group these elements with g tag and append path s and text s as a child for g elements. 您应该使用g标签将这些元素分组,并将path s和text附加为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;}
    );

In this case, your structure will look like: 在这种情况下,您的结构将如下所示:

<g>
 <path d=...></path>
 <text>some text</text>
</g>
<g>
 <path d=...></path>
 <text>some text</text>
</g>
...

Check working example: 检查工作示例:

 var w = 280; var h = 280; var r = h/2; var color = d3.scale.category20c(); var data = [{"label":"Category A", "value":20}, {"label":"Category B", "value":50}, {"label":"Category C", "value":30}]; var vis = d3.select('body').append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + r + "," + r + ")"); var pie = d3.layout.pie().value(function(d){return d.value;}); var arc = d3.svg.arc().outerRadius(r); var arcs = vis.selectAll("g.slice") .data(pie) .enter() .append("g") .attr("class", "slice"); arcs.append("path") .attr("fill", function(d, i){ return color(i); }) .attr("d", function (d) { return arc(d); }); 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;} ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM