【问题标题】:How to update D3.js bubble chart with real-time JSON data?如何使用实时 JSON 数据更新 D3.js 气泡图?
【发布时间】:2018-01-12 19:35:33
【问题描述】:

我正在学习 d3 并尝试将静态气泡图转换为动态版本,随着 JSON 的变化删除/添加气泡。

我想每 5 秒读取一次 JSON 文件并更新气泡图。我尝试将setInterval() 与以下代码一起使用,但它不起作用...

var inter = setInterval(function() {
  updateData();
}, 5000);

function updateData() {
  d3.json("sample.json", function(error, data) {
    if (error) throw error;

    //take in the json file
   root = d3.hierarchy(classes(data))
        .sum(function(d) { return d.value; })
        .sort(function(a, b) { return b.value - a.value; });
   console.log(root);
   bubble(root);

   node = svg.selectAll(".node")
       .data(root.children);

   node.exit().remove();

   //add new things into the file
   node.enter().append("g")
   .attr("class", "node")

   node.append("title")
       .text(function(d) { return d.data.className + ": " + format(d.value); });

   node.append("circle")
       .attr("r", function(d) { return d.r; })
       .style("fill", function(d) {
         return color(d.data.packageName);
       });

   node.append("text")
       .attr("dy", ".3em")
       .style("text-anchor", "middle")
       .text(function(d) { return d.data.className.substring(0, d.r / 3); });
  });
}
//==============================================================================
// updates end here

d3.select(self.frameElement).style("height", diameter + "px");

// Helper function definations
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: node.size});
  }

  recurse(null, root);
  return {children: classes};
}

我尝试将 root 打印到控制台,但没有更改

另外,我对AJAX知之甚少,是否有必要使用AJAX来更新JSON数据?

如果是这样,我应该如何使用 POST 方法来更新整个 JSON 文件?

【问题讨论】:

    标签: javascript json ajax d3.js


    【解决方案1】:

    可能是浏览器缓存。 试试这个:

    d3.json("sample.json?v="+Date.now(), function(error, data) { ...
    

    【讨论】:

      【解决方案2】:

      您正在检索一个文件,该文件的内容没有改变。

      d3.json("sample.json", [...]
      

      如果sample.json 没有变化,您的数据将保持不变。您需要一些服务器端处理来在该位置生成一个新的 json 文件,或者您需要使用某种 API 来检索动态值(可能来自数据库)。然后,您拥有的代码可以使用该数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-15
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        • 2018-12-08
        • 2016-03-01
        • 2015-04-09
        • 1970-01-01
        相关资源
        最近更新 更多