Labels on bilevel D3 partition / sunburst layout

前端 未结 3 721
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 09:35

I am trying to add labels to the bilevel sunburst / partition shown here - http://bl.ocks.org/mbostock/5944371:

<script

3条回答
  •  悲哀的现实
    2021-01-16 10:12

    Another D3 newbie, but I managed to resolve this. Beggining from the original Bilevel Partition:

    1. Add the text for the first time the chart is drawn:
    var path = svg.selectAll("path")
          .data(partition.nodes(root).slice(1))
        .enter().append("path")
          .attr("d", arc)
          .style("fill", function(d) { return d.fill; })
          .each(function(d) { this._current = updateArc(d); })
          .on("click", zoomIn);
    
    
    var text = svg.selectAll("text")
          .data(partition.nodes(root).slice(1))
        .enter().append("text")
        .attr("transform", function(d) { return "rotate(" + computeTextRotation(d) + ")"; })
        .attr("x", function(d) {return radius / 3 * d.depth; })
        .attr("dx", "6") // margin
        .attr("dy", ".35em") // vertical-align
        .html(function(d) { return d.name; });
    
    1. when zooming in or out you have to redraw labels, add the following in function zoom(root, p)
    text.enter().append("text")
        .attr("transform", function(d) { return "rotate(" + computeTextRotation(d) + ")"; })
        .attr("x", function(d) {return radius / 3 * d.depth; })
        .attr("dx", "6") // margin
        .attr("dy", ".35em") // vertical-align
        .text(function(d) { return d.name; });
    
    text.exit().transition()
        .style("fill-opacity", function(d) { return d.depth === 1 + (root === p) ? 1 : 0; })
        .remove();
    text.transition()
        .style("fill-opacity", 1)
        .attr("transform", function(d) { return "rotate(" + computeTextRotation(d) + ")"; })
        .attr("x", function(d) {return radius / 3 * d.depth; })
        .attr("dx", "6") // margin
        .attr("dy", ".35em") // vertical-align
    
    1. Finally modify the computeTextRotation function as:
    function computeTextRotation(d) {
      return (d.x + (d.dx)/2) * 180 / Math.PI - 90;
    }
    

    Hope I haven't missed anything.

提交回复
热议问题