Updating Elements Grouped under a SVG:G

your feedback

This in response to a SO question but it is also a good opportunity to briefly demonstrate how to apply D3's update/exit/pattern when elements are grouped under a svg:g element. This is a common situation although it is a bit different than using the pattern against elements that are NOT grouped.

DIVs can paint a thousand words :)
So, if you click on the different datasets below you will see that the bars and associated text update correctly.

data1
data2
data3

And here is the main section of code to make it happen:

						// dataset 1, the 2 other datasets have different count values
						var data1 = [
							{"name": "AGE SUM", "id": 0, "count": 98},
							{"name": "father", "id": 2, "count": 57},
							{"name": "mother", "id": 1, "count": 41}
						];

						...

						var g = svg.selectAll("g")
							.data(data, function(d) {return d.count;});

						g.exit().remove(); // g exit selection

						var gEnter = g.enter() // g enter selection (captured for appending elements)
							.append("g")
							.classed("g",true);

						gEnter // appending rect elements off the g enter selection
							.append("rect")
							.classed("rect",true);

						g.select(".rect") // updating rect elements
							.attr("x",0)
							...

						gEnter // appending text elements off the g enter selection
							.append("text")
							.classed("text",true);

						g.select(".text") // updating text elements
							.attr("x",function(d) {return d.count + 2;})
							...
					

Two important notes here:

Well, I sincerely hope this is clear. I will leave you with an excellent starting point for understanding the enter/update/exit pattern:

Thanks for dropping by.

May 8, 2014