Search code examples
javascriptd3.jsrotationicicle-diagram

How to get the rotation of a text label in the Zoomable Icicle Layout in D3?


I have added labels to the Zoomable Icicle Layout example provided here: http://bl.ocks.org/mbostock/1005873

I rotate the labels based on available space using the following:

.attr("transform", function (d) {
     return (x(d.x + d.dx) - x(d.x)) > 50 ?
          ("translate(" + (x(d.x + d.dx / 2)) + "," + (y(d.y + d.dy / 2)) + ")rotate(0)") :
          ("translate(" + (x(d.x + d.dx / 2)) + "," + (y(d.y + d.dy / 2)) + ")rotate(90)"); })

which rotates the label 90' if the space is too small to keep it horizontal.

What I would like to know is how to get the rotation value of each d?


Solution

  • You can abstract out the code which determines the rotation angle simplify the expression as:

    function rotation(d, x) {
        return (x(d.x + d.dx) - x(d.x)) > 50 ? 0 : 90;
    }
    
    // ...
    .attr("transform", function (d) {  
          return "translate(" + [(x(d.x + d.dx / 2)), (y(d.y + d.dy / 2))] + ")" +  
                 "rotate(" + rotation(d, x) + ")";
    })
    

    Then whenever you need the value of rotation of a point which is bound to data d, call rotation(d, x).