I\'m trying to make a pie chart with d3.js
that looks like this:
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 path
s 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.