Issue labeling d3 sunburst

2.1k Views Asked by At

I am developing a d3 sunburst type.

Everything is ok, It is taking the flare JSON correctly but, when I go to label the path look what is happening:

enter image description here

The code is the following:

var width = 960,
    height = 700,
    radius = Math.min(width, height) / 2;

var x = d3.scale.linear()
    .range([0, 2 * Math.PI]);

var y = d3.scale.linear()
    .range([0, radius]);

var hue = d3.scale.ordinal().range(["#feec76","#aec7e8","#ff00bf","#7f7f7f"]);

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

var partition = d3.layout.partition()
    .value(function(d) { return d.size; });

var arc = d3.svg.arc()
    .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
    .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
    .innerRadius(function(d) { return Math.max(0, y(d.y)); })
    .outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); });

d3.json("http://api.printoriente.com/treemap.php", function(error, root) {
  var g = svg.selectAll("g")
      .data(partition.nodes(root))
    .enter().append("g");

  var path = g.append("path")
    .attr("d", arc)
    .style("fill", function(d) { return hue((d.children ? d : d.parent).name); })
    .on("click", click);

  var text = g.append("text")
    .attr("transform", function(d) { return "rotate(" + computeTextRotation(d) + ")"; })
    .attr("x", function(d) { return y(d.y); })
    .attr("dx", "6") // margin
    .attr("dy", ".35em") // vertical-align
    .text(function(d) { return d.name; });

And the rotation code is:

function computeTextRotation(d) {
  return (x(d.x + d.dx / 2) - Math.PI / 2) / Math.PI * 180;
}

This script works for all others d3 but I have to put those colors for each path.

Where is the problem?

Regards.

UPDATED: d3 sunburst with small font-size:

enter image description here

UPDATED: I want something like this:

enter image description here

UPDATED: Take a look of internal labels:

enter image description here

1

There are 1 best solutions below

0
On

I'm not sure where you got the code to calculate the angle from, but it seems to be completely off. If you look at this example, the code to compute the angle is (with everything else being equal)

var angle = (d.x + d.dx / 2) * 180 / Math.PI - 90;

Replacing the code in your example with that fixes the angles. To fix the positions, you can adjust the dx offset of the labels, e.g.

.attr("dx", 50")

Complete example here.