d3.js 的饼图转换图中的输入数据未显示标签名称

Label names are not displayed from input data in pie transition chart of d3.js

我正在使用 d3.js 绘制饼图。但是当标签放置在数据数组中时,如下所示:

data = [{"label":"sector1", "value":25}, {"label":"sector2", "value":45}]  

饼图将不会显示。相反,将打印“NaN”。

完整代码贴在下面:

var w = 400,
h = 400,
r = Math.min(w, h) / 2,
data = [{"label":"sector1", "value":25}, {"label":"sector2", "value":45}],   // Data with label-value pairs
color = d3.scale.category20(),
arc = d3.svg.arc().outerRadius(r),
donut = d3.layout.pie();

var vis = d3.select("body").append("svg")  // Place the chart in 'pie-chart-div'
    .data([data])
    .attr("width", w)
    .attr("height", h);

var arcs = vis.selectAll("g.arc")
    .data(donut)
  .enter().append("g")
    .attr("class", "arc")
    .attr("transform", "translate(" + r + "," + r + ")");

var paths = arcs.append("path")
    .attr("fill", function(d, i) { return color(i); });

var labels = arcs.append("text")
      .attr("transform", function(d) { d.innerRadius = 120; return "translate(" + arc.centroid(d) + ")"; })
      .attr("dy", ".35em")
      .text(function(d) { return d.value; });

paths.transition()
    .ease("bounce")
    .duration(2000)
    .attrTween("d", tweenPie);

paths.transition()
    .ease("elastic")
    .delay(function(d, i) { return 2000 + i * 50; })
    .duration(750)
    .attrTween("d", tweenDonut);

function tweenPie(b) {
  b.innerRadius = 0;
  var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
  return function(t) {
    return arc(i(t));
  };
}

function tweenDonut(b) {
  b.innerRadius = r * .6;
  var i = d3.interpolate({innerRadius: 0}, b);
  return function(t) {
    return arc(i(t));
  };
} 


<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

如何在图表中显示标签名称和值?

您需要调用 donut 并包含您的数据:

data2 = data.map(function(d) { return d.value}) // [25, 45]
...
.data(donut(data2))

然后调用标签 ;

  .text(function(d, i) { return data[i].label; });

http://jsfiddle.net/980f0cdj/1/