How to update bubble chart in d3.js?

I managed to create a bubble chart that works great when it is a single dataset. But something is wrong if I need to update it with other datasets. Please help me with my update function at http://jsfiddle.net/9jL64/ .

function changebubble(root) { var node = svg.selectAll(".node") .data(bubble.nodes(classes(root)) .filter(function(d) { return !d.children; })); node.enter() .append("g") .attr("class", "node") .attr("transform", function (d) { return "translate(" + dx + "," + dy + ")"; }); node.select("circle") .transition() .duration(1000) .attr("r", function(d) { return dr; }) .style("fill", function(d,i) { return color(i); }); node.transition().attr("class", "node") .attr("transform", function(d) { return "translate(" + dx + "," + dy + ")"; }); node.append("circle") .attr("r", function (d) { return dr; }) .style("fill", function (d, i) { return color(i); }); node.exit() .remove(); // Returns a flattened hierarchy containing all leaf nodes under the root. function classes(root) { var classes = []; function recurse(name, node) { if (node.children) node.children.forEach(function(child) { recurse(node.name, child); }); else classes.push({packageName: name, className: node.name, value: node.size}); } recurse(null, root); return {children: classes}; } 
+4
source share
1 answer

This is a classic case when you need to fix the input selection in an element of the svg:g group in order to correctly apply the input / update / output template. But in order to keep the object constant , and so that your labels still point to the necessary elements, you also need to enter data based on some data property of interest ( d.className , which is generated from d.name ).

Here is the main segment of your updated bubble update feature:

 var node = svg.selectAll(".node") .data( bubble.nodes(classes(root)).filter(function (d){return !d.children;}), function(d) {return d.className} // key data based on className to keep object constancy ); // capture the enter selection var nodeEnter = node.enter() .append("g") .attr("class", "node") .attr("transform", function (d) { return "translate(" + dx + "," + dy + ")"; }); // re-use enter selection for circles nodeEnter .append("circle") .attr("r", function (d) {return dr;}) .style("fill", function (d, i) {return color(i);}) // re-use enter selection for titles nodeEnter .append("title") .text(function (d) { return d.className + ": " + format(d.value); }); 

Full FIDDLE is here.

I also blog on applying an input / update / exit pattern to svg:g elements if you are interested.

+7
source

All Articles