score:6

Accepted answer

You need to assign some form of key to the bars' data so d3 can identify ones that existed in the previous set. The default is index-based, and that may be what you want.

As far as the transitions go, you want to change your code to something like this:

bars = vis.selectAll("g.bar")
    .data(data);

bars.enter().append("svg:g")
    .attr("class", "bar")
    .append("svg:rect").

bars.transition().duration(500)
    .attr("transform", function(d, i) { 
         return "translate(" + labelpad + "," + y(i) + ")"; 
     })
    .selectAll("svg:rect")
    .attr("width", x)
    .attr("height", y.rangeBand())
;

bars.exit().transition().duration(500)
    .selectAll("svg:rect")
    .attr("height", 0)
    .remove();

The "enter()" function is best used to create the structure immediately. Then use the initial selection object (bars) to apply the new data to all elements.

You also probably want to remove any obsolete bars. Here I've resized them to 0 and then removed them, but you can tinker with it to get the effect you want.


Related Query

More Query from same tag