我使用 D3 创建了此层次结构图表,并且希望使其可折叠。我对 D3 还很陌生,所以我只是习惯于理解代码。我还需要增加节点之间的宽度,但我不知道该怎么做。目前文本相互重叠,这就是为什么我需要扩大每个节点之间的宽度。有人也可以帮忙解决这个问题吗?
D3代码:
var margin = {top: 40, right: 120, bottom: 20, left: 120},
width = 960 - margin.right - margin.left,
height = 500 - margin.top - margin.bottom;
var i = 0;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.x, d.y]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
root = treeData[0];
update(root);
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Length of the link
nodes.forEach(function(d) { d.y = d.depth * 100; });
// Declare the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter the nodes.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
nodeEnter.append("circle")
.attr("r", 8)
.style("fill", "#fff");
nodeEnter.append("text")
.attr("y", function(d) {
return d.children || d._children ? -18 : 18;
})
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("fill-opacity", 1);
// Declare the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter the links.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", diagonal);
}
最佳答案
也许 Mike Bostock 在可折叠树上的工作会有所帮助 http://bl.ocks.org/mbostock/4339083
您可以观察到,添加折叠功能并将鼠标事件附加到节点即可使节点可折叠。
您还需要添加涉及nodeExit 和nodeUpdate 的代码。
要解决文本相互重叠的问题 - 观察您的代码,了解将文本附加到 nodeEnter 的部分。
nodeEnter.append("text")
.attr("y", function(d) {
return d.children || d._children ? -18 : 18;
})
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("fill-opacity", 1);
尝试使用 -18 : 18 的数字。增加这些数字可能有助于文本不相互重叠,因为这些数字会调整文本和节点的距离。您可能还想尝试一下“文本 anchor ”。试试这个:
nodeEnter.append("text")
.attr("x", function(d) {
return d.children || d._children ? -10 : 10;
})
.attr("dy", ".35em")
.attr('class', 'nodeText')
.attr("text-anchor", function(d) {
return d.children || d._children ? "end" : "start";
})
.text(function(d) {
return d.name;
})
.style("fill-opacity", 0);
最后,如果您真的想完全了解 D3 树,此链接是一个非凡的来源 http://www.d3noob.org/2014/01/tree-diagrams-in-d3js_11.html
关于javascript - 如何使我的 D3 可折叠图表可折叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31071388/