需要一些帮助D3饼图布局添加行标签

时间:2015-03-03 07:31:03

标签: javascript d3.js

以下是我希望看起来相似的图像示例: http://i.stack.imgur.com/ro2kQ.png

我正在制作饼图,但我想在该标签上添加一行 - >值。 任何帮助将不胜感激。

http://jsfiddle.net/28zv8n65/

这是;

arcs.append("svg:text")
  .attr("transform", function(d) { //set the label's origin to the center of the arc
    //we have to make sure to set these before calling arc.centroid
    d.outerRadius = outerRadius + 50; // Set Outer Coordinate
    d.innerRadius = outerRadius + 45; // Set Inner Coordinate
    return "translate(" + arc.centroid(d) + ")";
  })
  .attr("text-anchor", "middle") //center the text on it's origin
  .style("fill", "Purple")
  .style("font", "bold 12px Arial")
  .text(function(d, i) { return dataSet[i].label; });

1 个答案:

答案 0 :(得分:1)

试试这段代码。

var labelr = outerRadius+60;

//Draw labels

arcs.append("svg:text")
    .attr("text-anchor", "middle") //center the text on it's origin
    .style("fill", "Purple")
    .style("font", "bold 12px Arial")
    .text(function(d, i) { return dataSet[i].label; }) 
    .attr("x", function(d) {
        var a = d.startAngle + (d.endAngle - d.startAngle)/2 - Math.PI/2;
        d.cx = Math.cos(a) * (labelr - 75);
        return d.x = Math.cos(a) * (labelr - 20);
    })
    .attr("y", function(d) {
        var a = d.startAngle + (d.endAngle - d.startAngle)/2 - Math.PI/2;
        d.cy = Math.sin(a) * (labelr - 75);
        return d.y = Math.sin(a) * (labelr - 20);
    })
    .each(function(d) {      
        var bbox = this.getBBox();
        d.sx = d.x - bbox.width/2 - 2;
        d.ox = d.x + bbox.width/2 + 2;
        d.sy = d.oy = d.y + 5;
    });

//Draw pointer lines

arcs 
  .append("path")
  .attr("class", "pointer")
  .style("fill", "none")
  .style("stroke", "black")
  .attr("d", function(d) {     
    if(d.cx > d.ox) {
        return "M" + d.sx + "," + d.sy + "L" + d.ox + "," + d.oy + " " + d.cx + "," + d.cy;
    } else {
        return "M" + d.ox + "," + d.oy + "L" + d.sx + "," + d.sy + " " + d.cx + "," + d.cy;
    }
  });

代码来自d3.js pie chart with angled/horizontal labels