如何在气泡图中更新数据时保持svg内的圆圈

时间:2014-11-23 00:01:02

标签: javascript svg d3.js circle-pack

我正在尝试在气泡图中添加交互并在单击相应按钮时更新数据。但是当我点击按钮时出错了,圆圈超出了svg的界限。我无法弄清楚如何解决它。请帮忙!

这是工作Plunk。(尝试2006,2007或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);

非常感谢!

1 个答案:

答案 0 :(得分:1)

您的更新功能存在一些问题,仅举几个大问题:

  • 您选择的元素(var node = svg2.selectAll("circle"))与您输入的元素(var nodeEnter=node.enter().append("g"))不匹配。这在定义关键功能和执行数据连接时会导致问题
  • 在转换现有元素时,您似乎试图重新绑定数据(node.select("circle").data(pack.nodes,function(d) {return d.city}))这会导致问题 - 数据已绑定到这些元素,此时重新绑定是不必要的。 / LI>

我已在此处对您的代码进行了更新:http://plnkr.co/edit/pYQTCOKWXoRM3ZE0HEt3?p=preview