d3.js: 如何在圆环图中的标签下方添加值

d3.js: How to add value below the label in donut chart

我是 d3.js 的新手,到目前为止我所取得的成就是 this 使用教程和视频。

现在我尝试在标签文本下方添加dataset.value,如图所示。

var dataset = [{
  label: 'On trip',
  value: 35
}, {
  label: 'parked',
  value: 65 
}];

如何实现?

你需要这样做:

    var text = svg.select(".labels").selectAll("text")
        .data(pie(data), key);
  //make a group  
    var textg = text.enter().append("g");
  //to the group append text for label
    textg
        .append("text")
        .attr("dy", ".35em")
        .text(function(d) {
            return d.data.label;
        });
  //to the group append text for value  
    textg.append("text")
      .attr("dy", "1.95em")
      .text(function(d) { return d.data.value; });  

工作代码here

您可以使用以下代码更新附加文本代码。

text.enter()
 .append("text")
 .attr("dy", ".35em")
 .append('svg:tspan')
 .attr('x', 0)
 .attr('dy', 0)
 .text(function(d) { return d.data.label; })
 .append('svg:tspan')
 .attr('x', 0)
 .attr('dy', 20)
 .text(function(d) { return d.data.value; });

将两个 tspan 附加到您的 text 元素

已更新 Fiddle 此处