首页 > 解决方案 > 如何将新数据添加到 D3js 循环打包?

问题描述

我想在圆形包装力模拟中一点一点地添加新的圆圈。基于这个例子,我使用一个现有的数据数组做了一个循环包装力模拟:https ://www.d3-graph-gallery.com/graph/circularpacking_template.html

如何在保持模拟活动的同时在圆形包装中添加新数据(新圆圈)?

let dataset = [{ data: 3997, type: "file_1" },{ data: 39879, type: "file_2" }];

var width = 450;
var height = 370;

var svg = d3
  .select("#my_dataviz")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var max = d3.max(dataset, function (d) {
  return d.data;
});

var size = d3.scaleSqrt().domain([0, max]).range([2, 35]);

var node = svg
  .append("g")
  .selectAll("circle")
  .data(dataset)
  .enter()
  .append("circle")
  .attr("r", function (d) {
    return size(d.data);
  });

var simulation = d3
  .forceSimulation(node)
  .force("charge", d3.forceManyBody().strength(2))
  .force("center", d3.forceCenter(width / 2, height / 2))
  .force(
    "collision",
    d3.forceCollide().radius(function (d) {
      return size(d.data) + 2;
    })
  );

simulation.nodes(dataset).on("tick", function (d) {
  node
    .attr("cx", function (d) {
      return d.x;
    })
    .attr("cy", function (d) {
      return d.y;
    });
});

标签: javascriptd3.jsdata-visualization

解决方案


推荐阅读