d3.js正在更新visual

d3.js updating visual

本文关键字:更新 visual js d3      更新时间:2023-09-26

我有一个与d3.js组合在一起的树图。我通过getJSON填充数据。它非常有效。然而,我在setInterval方法中有这个功能,它似乎并没有刷新自己。

    var treemap = d3.layout.treemap()
.padding(4)
.size([w, h])
.value(function(d) { return d.size; });
var svg = d3.select("#chart").append("svg")
.style("position", "relative")
.style("width", w + "px")
.style("height", h + "px");

function redraw3(json) {
  var cell = svg.data([json]).selectAll("g")
      .data(treemap)
    .enter().append("g")
      .attr("class", "cell")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
  cell.append("rect")
      .attr("width", function(d) { return d.dx; })
      .attr("height", function(d) { return d.dy; })
      .style("fill", function(d) { return d.children ? color(d.data.name) : null; });
  cell.append("text")
      .attr("x", function(d) { return d.dx / 2; })
      .attr("y", function(d) { return d.dy / 2; })
      .attr("dy", ".35em")
      .attr("text-anchor", "middle")
      .text(function(d) { return d.children ? null : d.data.name; });
}

setInterval(function() {
d3.json("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
redraw3(json);
});
}, 3000);

我的问题是,为什么当我更改json文件中的数据时,它不会在3秒钟后显示在树图中?

提前谢谢。

数据中有什么?因为如果数据数组具有相同的长度,则enter()选择(对应于先前未绑定的数据)的长度将为零。Mike Bostock写了一个很棒的教程,叫做Thinking with Joins,我建议你在继续之前先读一读。

svg.data()调用似乎是多余的,为了清楚起见,我建议这样做:

var leaves = treemap(json);
console.log("leaves:", leaves); // so you can see what's happening
// cell here is the bound selection, which has 3 parts
var cell = svg.selectAll("g")
  .data(leaves);
// you might want to console.log(cell) here too so you can take a look
// 1. the entering selection is new stuff
var entering = cell.enter()
  .append("g")
entering.append("rect")
  // [update rectangles]
entering.append("text")
  // [update text]
// 2. the exiting selection is old stuff
cell.exit().remove();
// 3. everything else is the "updating" selection
cell.select("rect")
  // [update rectangles]
cell.select("text")
  // [update text]

你也可以将单元格的更新封装在一个函数中,并在输入和更新选择时"调用"它,这样你就不必写两次相同的代码:

function update() {
  cell.select("rect")
    // [update rectangles]
  cell.select("text")
    // [update text]
}
entering.append("rect");
entering.append("text");
entering.call(update);
cell.call(update);