Search code examples
d3.jstransitionupdatesdonut-chart

D3.js Donut transition


I am working on a d3 donut and am stuck on how to update the donut value where the value will flow back if for instance you change the value from 42 to 17. I can remove the svg, but then it rewrites the new value (17) from the zero position.

I would like it to flow backwards from 42 say to 17.

var path = svg.selectAll("path")
        .data(pie(dataset.lower))
        .enter().append("path")
        .attr("class", function(d, i) { return "color" + i })
        .attr("d", arc)
        .each(function(d) { this._current = d; }); // store the initial values

here is a link to my jsfidle http://jsfiddle.net/yr595n96/

and I would love any help you could offer.

Thanks


Solution

  • Heres you're new button click :

    $("#next").click(function () {
        percent = 17;
        var progress = 0;
        var timeout = setTimeout(function () {
            clearTimeout(timeout);
            var randNumber = Math.random() * (100 - 0 + 1) + 0;
            //path = path.data(pie(calcPercent(17))); // update the data << change this
            path = path.data(pie(calcPercent(randNumber)));
            path.transition().duration(duration).attrTween("d", function (a) {
                // 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.
                var i  = d3.interpolate(this._current, a);
                var i2 = d3.interpolate(progress, randNumber)
                this._current = i(0);
                return function(t) {
                    text.text( format(i2(t) / 100) );
                    return arc(i(t));
                };
            }); // redraw the arcs
        }, 100);
    });
    

    Notice on line '8':

    path = path.data(pie(calcPercent(randNumber)));
    

    You need to pass new data for it to transition to. I have used a random number here just to show you any number works. I made a variable for this and passed it to both the 'path' and the text : 'i2' > d3.interpolate.

    You can always just change it to 17 to suit what you asked for :)

    Updated fiddle : http://jsfiddle.net/yr595n96/3/