How to update both the content and location of text labels on a D3 pie chart

前端 未结 1 1917
离开以前
离开以前 2021-01-29 13:07

I\'m trying to make a pie chart with d3.js that looks like this:

\"enter

1条回答
  •  长情又很酷
    2021-01-29 14:01

    When updating the text elements, you also need to update the data that's bound to them, else nothing will happen. When you create the elements, you're binding the data to the g element that contains the arc segment and text. By then appending path and text, the data is "inherited" to those elements. You're exploiting this fact by referencing d when setting attributes for those elements.

    Probably the best way to make it work is to use the same pattern on update. That is, instead of updating only the data bound to the path elements as you're doing at the moment, update the data for the g elements. Then you can .select() the descendant path and text elements, which will again inherit the new data to them. Then you can set the attributes in the usual manner.

    This requires a few changes to your code. In particular, there should be a variable for the g element selection and not just for the paths to make things easier:

    var g = svg.selectAll("g.arc")
            .data(pie(data));
    g.enter()
            .append("g").attr("class", "arc");
    var path = g.append("path");
    

    The changeFunction code changes as follows:

    var gnew = g.data(pie(data));
    gnew.select("path")
                .transition()
                .duration(750)
                .attrTween("d", arcTween);
    

    Now, to update the text, you just need to select it and reset the attributes:

    gnew.select("text")
        .attr("transform", function(d) { ... });
    

    Complete demo here.

    0 讨论(0)
提交回复
热议问题