How to Update bubble chart in d3.js?

I managed to create a bubble chart which works fine when it is a single dataset. But something goes wrong if I need to update it with other datasets. Please help me with my update function at

function changebubble(root)
  var node = svg.selectAll(".node")
      .filter(function(d) { return !d.children; }));

    .attr("class", "node")
    .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });"circle")
    .attr("r", function(d) { return d.r; })
    .style("fill", function(d,i) { return color(i); });

   node.transition().attr("class", "node")
     .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

     .attr("r", function (d) { return d.r; })
     .style("fill", function (d, i) { return color(i); });


// 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(, child); });
      classes.push({packageName: name, className:, value: node.size});

  recurse(null, root);
  return {children: classes};



This is the classic case when you need to capture the enter selection on the svg:g group element in order to apply the enter/update/exit pattern correctly. But, to keep object constancy, and so that your labels still point to the right elements, you also need to key your data based on some data property of interest (d.className, which is generated from

Here is the main segment of your revised bubble update function:

var node = svg.selectAll(".node")
        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()
    .attr("class", "node")
    .attr("transform", function (d) {
        return "translate(" + d.x + "," + d.y + ")";

// re-use enter selection for circles
    .attr("r", function (d) {return d.r;})
    .style("fill", function (d, i) {return color(i);})

// re-use enter selection for titles
    .text(function (d) {
        return d.className + ": " + format(d.value);

The complete FIDDLE is here.

I also blogged on the matter of applying the enter/update/exit pattern to svg:g elements, if you are interested.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.