简体   繁体   中英

Adding labels to a 3D pie chart in D3.js

I'm trying to recreate the 3D pie chart in this example: http://bl.ocks.org/NPashaP/9994181

Here's my version: http://jsfiddle.net/26v6cc8x/1/

var salesData=[
    {label:"Basic", color:"#3366CC"},
    {label:"Plus", color:"#DC3912"},
    {label:"Lite", color:"#FF9900"},
    {label:"Elite", color:"#109618"},
    {label:"Delux", color:"#990099"}
];

var svg = d3.select("body").append("svg").attr("width",700).attr("height",400);

svg.append("g").attr("id","quotesDonut");

Donut3D.draw("quotesDonut", randomData(), 450, 150, 250, 150, 50, 0);

function changeData(){
    Donut3D.transition("quotesDonut", randomData(), 250, 150, 50, 0);
}

function randomData(){
    return salesData.map(function(d){ 
        return {label:d.label, value:1000*Math.random(), color:d.color};});
}

 $(".btn-change").click(function(){
        changeData();
 });

My question is, how do I add the actual data labels (not the calculated percentages) outside the pie and make sure they keep their correct position after transition? Meaning I want both percentages and labels to show up.

Any help is greatly appreciated. Thanks!

In the Donut3D.js change the following function:

function getPercent(d){
  return (d.endAngle-d.startAngle > 0.2 ? 
  Math.round(1000*(d.endAngle-d.startAngle) / (Math.PI * 2)) /10 + '%' : '');
}   

To this:

function getPercent(d) {
  return (d.endAngle - d.startAngle > 0.2 ?
  d.data.label + ': ' + Math.round(1000 * (d.endAngle - d.startAngle) / (Math.PI * 2)) / 10 + '%' : '');}

This will prefix the label to the percentage value that shows in the graph.

Hope this helps!

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