I discussed an example circle. However, I have a lot of problems trying to update this thing from a new JSON dataset and then update it.
My code is just a modified version of the sample district package:
var diameter = 960, format = d3.format(",d"); var pack = d3.layout.pack() .size([diameter - 4, diameter - 4]) .value(function(d) { return d.size; }); var svg = d3.select("body").append("svg") .attr("width", diameter) .attr("height", diameter) .append("g") .attr("transform", "translate(2,2)"); var node; d3.json("data1.json", function(error, root) { node = svg.datum(root).selectAll(".node") .data(pack.nodes); node.enter().append("g") .classed("node", true) .attr("transform", function(d) { return "translate(" + dx + "," + dy + ")"; }); node.append("title") .text(function(d) { return d.name; }); node.append("circle") .attr("r", 0) .on("click", refresh) .transition() .duration(2000) .attr("r", function(d) { return dr; }); node.append("text") .attr("dy", ".3em") .style("text-anchor", "middle") .text(function(d) { return d.name }); node.exit() .remove(); }); d3.select(self.frameElement).style("height", diameter + "px");
This works as expected. However, I want to make an update function that updates the chart from the new JSON data and is updated. I tried the code below, but it just adds a new element instead of replacing the old ones and also does not delete the old ones (node.exit.remove () apparently never starts). I am wondering if this is due to the use of "datum" instead of "data" and is the data connection really made in this regard:
var refresh = function() { d3.json("data2.json", function(error, root2) { node = svg.datum(root2).selectAll(".node") .data(pack.nodes); node.append("title") .text(function(d) { return d.name; }); node.append("circle") .attr("r", 0) .transition() .duration(2000) .attr("r", function(d) { return dr; }); node.append("text") .attr("dy", ".3em") .style("text-anchor", "middle") .text(function(d) { return d.name }); }); }
It is very difficult for me to figure out exactly how the data is attached to the package and how to update it. I probably once again missed something simple, but any help would be greatly appreciated, since it was difficult for me to find a sample to illustrate this. I will gladly do it for others in the future if someone can help me here. :)
To write the data that I use is:
{ "name": "Names", "children": [ { "name": "John", "size": 100 }, { "name": "Peter", "size": 200 }, { "name": "Arnold", "size": 300 }, { "name": "Rasmus", "size": 400 } ] }
and
{ "name": "Names", "children": [ { "name": "John", "size": 1000 }, { "name": "Rasmus", "size": 200 }, { "name": "Benjamin", "size": 300 }, { "name": "James", "size": 400 } ] }