Arthur
Arthur

Reputation: 1

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

I am learning d3 and tried to convert a static bubble chart into a dynamic version, removing/adding bubbles as the JSON changes.

I want to read the JSON file every 5 seconds and update the bubble chart. I tried using setInterval() with the following code but it is not working...

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};
}

I tried to print root to the console, and it wasn't changed

Besides, I only know little about AJAX, is it necessary to use AJAX to update the JSON data?

If so, how should I use the POST method to update the whole JSON file?

Upvotes: 0

Views: 604

Answers (2)

Daan
Daan

Reputation: 10304

It looks like you are retrieving a file, of which the content does not change.

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

If sample.json is not changing, your data will remain the same. You need some server side processing to generate a new json file in that location, or you need to use some kind of API to retrieve dynamic values (maybe out of a database). The code you have could then use that data.

Upvotes: 0

Oleg Pnk
Oleg Pnk

Reputation: 332

May be it is browser cache. Try this:

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

Upvotes: 1

Related Questions