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

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

本文关键字:svg 保留 气泡 数据 更新      更新时间:2023-09-26

>我正在尝试在气泡图中添加交互并在单击相应按钮时更新数据。但是当我单击按钮时,sth 出错了,圆圈超出了 svg 的范围。我不知道如何解决它。请帮忙!

这是工作的普伦克。(尝试 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);

多谢!

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

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

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