简体   繁体   中英

adding text in d3.js multi level pie chart

I want to have a multi level pie chart such as here:

The only thing I am not getting to work is how to add text to the pie chart. I want each segment to have a label on it. Now I know how to do this for a single level pie chart but I am not succeeding in this multi level one. If someone could for instance show one example on jsfiddle that would be much appreciated!

http://jsfiddle.net/Qh9X5/304/

CSS

body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: auto;
  position: relative;
  width: 960px;
}

text {
  font: 10px sans-serif;
}

form {
  position: absolute;
  right: 10px;
  top: 10px;
}

Javascript

var dataset = {
  apples: [33.3, 33.3, 33.4],
  oranges: [12.5, 12.5, 12.5, 12.5, 12.5, 12.5, 12.5, 12.5],
  lemons: [20, 20, 20, 20, 20],
};

var width = 660,
    height = 500,
    cwidth = 75;

var color = d3.scale.category20();

var pie = d3.layout.pie()
    .sort(null);

var arc = d3.svg.arc();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var gs = svg.selectAll("g").data(d3.values(dataset)).enter().append("g");
var path = gs.selectAll("path")
    .data(function(d) { return pie(d); })
  .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", function(d, i, j) { return arc.innerRadius(10+cwidth*j).outerRadius(cwidth*(j+1))(d); });

d3.svg.arc.centroid is a convenient way to get a point at the center of an arc, which is an OK starting point for labels.

Here's another similar question that shows some additional positioning. Label outside arc (Pie chart) d3.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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