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("")

    .attr("class", "bar")

    .attr("transform", function(d, i) { 
         return "translate(" + labelpad + "," + y(i) + ")"; 
    .attr("width", x)
    .attr("height", y.rangeBand())

    .attr("height", 0)

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