请参阅http://bl.ocks.org/mbostock/4339083 它从flare.json加载数据并以树形布局显示节点。我想做以下事情: 1.编写一个函数,根据某些条件只显示部分节点并重新加载树。 2.编写一个函数来添加一些节点并重新加载树。 3.编写一个函数来删除一些节点并重新加载树。
我需要从外面调用这些函数 d3.json(“/ d / 4063550 / flare.json”,函数(错误,耀斑) 在那个样本中。
请告诉我怎么做。我尝试了.children.splice方法并再次调用upload(root)。但它没有用。
以下是代码的相关部分:
d3.json("/d/4063550/flare.json", function(error, flare) {
root = flare;
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
});
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
答案 0 :(得分:0)
我改变了你的代码,它对我有用:
d3.json("flare.json", function(json) {
root = json;
root.fixed = true;
root.x = w / 2;
root.y = h / 2 - 80;
console.log("haha");
firstTimeRun();
update();
});
function firstTimeRun(){
flatten(root).forEach(collapse);
}
function collapse(d) {
if (d.children) {
d._children = d.children;
d.children = null;
}
}