Search code examples
d3.jsgraphdata-visualizationpie-chartupdating

D3 Pie chart not updating correctly


I got the following D3 v4 pie chart, every time I try updating it the data doesn't update correctly. I have been reading around tried following some other example, but just can't seem to get it to work. Current update function looks like this:

function PieGenUpdater(data, colourRangeIn) {
    var dataset = data;
    var width = 400;
    var height = 400;
    var radius = Math.min(width, height) / 2;

    var arc = d3.arc()
                .innerRadius(radius/1.5)
                .outerRadius(radius);

    var pie = d3.pie()
                .value(function(d) { return d.percent; })
                .sort(null);

    var svg = d3.select('#c-pie');

    var path = svg.selectAll('path').data(pie(dataset));

    path.enter()
        .append("path")
        .attr('fill', function(d, i) {
            return d.data.color;
        })
        .attr("d", arc)
        .each(function(d) {this._current = d;} );

    path.transition()
        .attrTween("d", arcTweenCoverage);

    path.exit().remove();
    // Store the displayed angles in _current.
    // Then, interpolate from _current to the new angles.
    // During the transition, _current is updated in-place by d3.interpolate.
    function arcTweenCoverage(a) {
      var i = d3.interpolate(this._current, a);
      this._current = i(0);
      return function(t) {
        return arc(i(t));
      };
    }

}

https://jsfiddle.net/mahsan/zup6kafk/

Any help is greatly appreciated.


Solution

  • Here is the 4 years too late answer...

    In PieGenUpdater change

    var path = svg.selectAll('path').data(pie(dataset));
    

    to

    var path = svg.select('g').selectAll('path').data(pie(dataset));
    

    In your update function you were adding the additional paths from dataset 1 directly under element instead of the element