How to keep circles inside the svg when updating data in bubble chart

735 views Asked by At

I am trying to add interaction in the bubble chart and update data when clicking on the according button. But sth goes wrong when I click the button, the circles go out of the bound of the svg. I can't figure out how to fix it. Please help!

Here is the working Plunk.(Try 2006,2007 or 2008)

function changebubble(i) {

d3.csv("count_s.csv", function(csvData) {

pack.value(function(d){var valuedata=[d.count2006, d.count2007, d.count2008];
return valuedata[i];});

var data = { name: "city", children: csvData };

var node = svg.data([data]).selectAll("circle")
  .data(pack.nodes);

var nodeEnter=node.enter().append("g")
    .attr("class", "node").attr("cx",0).attr("cy",0)
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });


nodeEnter.append("title")
    .text(function(d) { return d.city+ " : " +format(d.value); });


nodeEnter.append("circle")
    .attr("r", function(d) { return d.r; })
    .style("fill", function(d) { return color(d.city); });


 nodeEnter.append("text")
    .attr("dy", ".3em")
    .style("text-anchor", "middle")
    .text(function(d) { return d.city });

node.select("circle")
    .transition().duration(1000)
   .attr("r", function(d) { return d.r; })
    .style("fill", function(d) { return color(d.city); });

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

 node.select("text")
    .transition().duration(1000)
    .attr("dy", ".3em")
    .style("text-anchor", "middle")
    .text(function(d) { return d.city });

node.select("title")
.transition().duration(1000)
 .text(function(d) { return d.city+ " : " +format(d.value); });

node.exit().remove();

 });

 }

function updateBubble1() {changebubble(0);}
function updateBubble2() {changebubble(1);}
function updateBubble3() {changebubble(2);}

d3.select("#count2006").on("click",updateBubble1);
d3.select("#count2007").on("click",updateBubble2);
d3.select("#count2008").on("click",updateBubble3);

Thanks a lot!

1

There are 1 answers

1
Josh On BEST ANSWER

There are some problems with your update function, to name a couple of big ones:

  • The elements you are selecting (var node = svg2.selectAll("circle")) do not match the elements you are 'entering' (var nodeEnter=node.enter().append("g")). This leads to problems when defining key functions and performing data joins
  • You seem to be trying to rebind the data when transitioning existing elements (node.select("circle").data(pack.nodes,function(d) {return d.city})) This will cause problems -- the data is already bound to these elements and re-binding is un-necessary at this point.

I've made updates to your code here: http://plnkr.co/edit/pYQTCOKWXoRM3ZE0HEt3?p=preview