Home How to update d3js bubble chart with real-time json data
Reply: 1

How to update d3js bubble chart with real-time json data

Arthur
1#
Arthur Published in 2018-01-12 19:35:33Z

I was 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, and tried 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 in console, and it wasn't changed

Besides, I only know few 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?

Thanks for all help in advance

Oleg Pnk
2#
Oleg Pnk Reply to 2018-01-13 12:01:55Z

May be it is browser cache. Try this:

d3.json("sample.json?v="+Date.now(), function(error, data) { ...
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.295056 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO