Merge combines one selection with another as follows:
selectionCombined = selection1.merge(selection2);
You aren’t providing a second selection, so you aren’t merging anything. The selection you do have you are calling .merge()
on is the enter selection, returned by .enter()
– unless you add new slices to the pie, this will be empty every update after the first. As you aren’t merging anything with the enter selection, post merge the selection is still empty.
The enter selection is used to create elements so that for every item in the data array there is one corresponding element in the DOM – as you already have slices, only the update selection is not empty.
The update selection is that returned by .data()
, it contains existing elements which correspond to items in the data array. You want to merge this selection with the one returned by .enter()
:
var update = svg.selectAll("path")
.data(pie)
var enter = update.enter()
.append('path')
var merged = update.merge(enter)
However, a transition needs a start value and an end value. In your case you are trasitioning the d
attribute of a path. On update the start value is the path’s current d
and the end value is a d
representing the new value for the slice. On initial entry, what is the value that the transition should start from? It may be more appropriate to only transition on update:
var arc = d3.arc().innerRadius(0).outerRadius(radius);
var update = svg.selectAll("path")
.data(pie)
var enter = update.enter()
.append('path')
// Set initial value:
.attr('d', arc)
// If these values don't change, set only on enter:
.attr('fill', function(d,i){ return color[i] })
.attr("stroke", "black")
.style("stroke-width", "2px")
update.transition()
// transition existing slices to reflect new data.
.attr('d',arc)
Note: transitioning paths can be difficult – you’ll notice the deformity to the pie in the transition in your example. This is because of how the d
attribute string is interpolated. If you want to preserve the radius a different approach is needed in applying the transition.
CLICK HERE to find out more related problems solutions.