D3.js visual update

I have a treemap that I put together with d3.js. I populate the data via getJSON. It works great. However, I have this function in the setInterval method, and it does not seem to refresh itself.

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(" + dx + "," + dy + ")"; }); 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); 

My question is specifically, why, when I change the data in the json file, it does not appear after 3 seconds in the treemap?

Thanks in advance.

+1
source share
1 answer

What is in the data? Because if the data array has the same length, choosing enter() (which corresponds to previously unrelated data) will have a length of zero. Mike Bostock wrote a great tutorial called Joins Thinking , which I would recommend reading before moving on.

Calling svg.data() seems redundant, and for clarity, I recommend doing this instead:

 var leaves = treemap(json); console.log("leaves:", leaves); // so you can see what 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] 

You can also encapsulate cell updates in a function and β€œcall” it both during input and during the update, so you do not need to write the same code twice:

 function update() { cell.select("rect") // [update rectangles] cell.select("text") // [update text] } entering.append("rect"); entering.append("text"); entering.call(update); cell.call(update); 
+3
source

Source: https://habr.com/ru/post/1411582/


All Articles