score:1

I think your code could be modified as follow (untested, so unsure):

var data = [2, 4, 8]

var g = d3.select('svg').selectAll('.g').data(data);

// do stuff to the entering group
var enterSelection = g.enter();
var enterG = enterSelection.append('g')
 .attr('class', 'g');

//Append circles only to new elements
enterG.append('circle')
  .attr('class', 'circle')
  .attr('r', function(d) { return d })

// for each of the enter and updated groups, adjust the radius of the child circles 
enterG.merge(g)
  .select('.circle')
  .transition()
  .attr('r',function(d){return d*2});
g.exit().remove()

When using the first .selectAll, only existing elements are selected. Then, by entering, you are creating new elements, that generate a new selection. When you need to update all, you simply merge the new and existing elements in a single selection.

From that selection, I simply selected all .circle (single select - one element per g), and then update the radius thanks to the binding API that prevents me from making a .each call. I am unsure as how these two compares, I simply always did it this way.

Finally, here is a bl.ocks demonstrating the pattern.


Related Query

More Query from same tag