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

瘦欲@ 提交于 2020-01-24 11:58:05

问题


I am new to d3.js and what I have achieved till now is, this using tutorials and videos.

Now I am trying to add the dataset.value below the label text as shown in the figure.

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

How do I achieve this?


回答1:


You can update your append text code with following code.

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

Append two tspan to your text element

Updated Fiddle here




回答2:


You need to do it like this:

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

Working code here



来源:https://stackoverflow.com/questions/35868310/d3-js-how-to-add-value-below-the-label-in-donut-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!