I am currently working on implementing the example found at http://bl.ocks.org/mbostock/1093130. The goal is to have the "update" function redraw the graph with a completely different dataset each time a button on the DOM is pressed. I have made some modifications to the example in order to achieve this. Let's say I want to randomly populate the graph with JSON datasets whose names are stored in an array:
var array = ["graph.json","graph2.json"];
function reload() {
var rnd = Math.floor(Math.random()*2);
d3.json(array[rnd], function(error, json) {
if (error) throw error;
root = json;
update();
});
}
However, whenever the graph is redrawn, there seems to be a bug where nodes from the previous dataset still appear. I have tried various methods to remove elements from the container before calling update(), but none of them seem to work. After researching, I came across the data() function that uses a join approach to update the graph with changes in the data. Although this approach is useful for dynamic updates, it does not suit my needs. I then tried using datum() instead of data() as it was suggested for non-dynamic layouts, and removed the enter() and exit() calls accordingly. While the code compiles without errors, nothing is rendered on the screen. Here is the updated update() function:
function update() {
var nodes = flatten(root),
links = d3.layout.tree().links(nodes);
// Restart the force layout.
force
.nodes(nodes)
.links(links)
.start();
// Update links.
link = link.datum(links, function(d) { return d.target.id; });
link.insert("line", ".node")
.attr("class", "link");
// Update nodes.
node = node.datum(nodes, function(d) { return d.id; });
var nodeEnter = node.append("g")
.attr("class", "node")
.on("click", click)
.call(force.drag);
nodeEnter.append("circle")
.attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });
nodeEnter.append("text")
.attr("dy", ".35em")
.text(function(d) { return d.name; });
node.select("circle")
.style("fill", color);
}
Any help or guidance on this issue would be greatly appreciated.
https://i.stack.imgur.com/wzhv5.png
In the image above, you can see that the displayed data does not match the dataset. It should show names like "Mike", "Mike Jr.", "Paul"... and when collapsing nodes by clicking the root node, some of the data gets corrected, but not the data on the root node itself.
Here is the correct data that should be displayed:
//Second graph
{
"name": "Mike",
"children": [
{
"name": "Mike Jr.",
"children": [
{
"name": "Paul",
"children": [
{"name": "Peter", "size": 743}
]
}
]
}
]
}