d3.js更新视觉

时间:2012-03-10 20:34:07

标签: javascript jquery jquery-ui d3.js

我有一个与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秒后出现在树形图中?

提前谢谢。

1 个答案:

答案 0 :(得分: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);