簡體   English   中英

如何使用實時JSON數據更新D3.js氣泡圖?

[英]How to update D3.js bubble chart with real-time JSON data?

我正在學習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};
}

我嘗試將根目錄打印到控制台,但沒有更改

此外,我對AJAX知之甚少,是否有必要使用AJAX更新JSON數據?

如果是這樣,我應該如何使用POST方法來更新整個JSON文件?

可能是瀏覽器緩存。 嘗試這個:

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

似乎您正在檢索文件,其內容未更改。

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

如果sample.json不變,則您的數據將保持不變。 您需要進行一些服務器端處理才能在該位置生成一個新的json文件,或者您需要使用某種API來檢索動態值(可能從數據庫中檢索出來)。 然后,您擁有的代碼可以使用該數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM