javascriptd3.jschartstext-rotation

Text rotation within an arc using D3JS


I've created a chart using D3JS, and it's working fine. However, I want to set a different text rotation within the arcs, and I'm not being able to figure out how.

The left chart contains the current alignment. The right chart is the desired one. Only the text rotation is missing.

Current and Desired Text alignment - Image

HTML Code and Json Data: https://dl.dropboxusercontent.com/u/75479878/HtmlAndJson.zip

I think that's the piece of code I need to change, but don't know how:

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

Solution

  • You need to rework a few things to get the effect you want. The text labels are rotated with respect to the whole figure. Instead, place them in the center of each arc using arc.centroid and then rotate them "locally".

    First, here's the angle you desire (the angle of the arc):

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

    Second, here's the placement and rotate call:

      var text = g.append("g")
        .attr("transform", function(d){
          return "translate(" + arc.centroid(d) + ")";
        })
        .append("text")
        .attr("transform", function(d) {
          return d.parent ? "rotate(" + computeTextRotation(d) + ")" : "";
        })
        .style("text-anchor", "middle")
        .attr("dy", ".35em") // vertical-align
        .style("fill", function(d) {
          return d.textcolor ? d.textcolor : "#000";
        })
        .text(function(d) {
          if (d.parent) {
            return d.name;
          } else {
            aux = d.description;
            return "";
          }
        });
    

    Working example here