[英]Add labels to nodes in Hobbelt's “Group/Bundle Nodes” D3 force layout example?
我改编了 Ger Hobbelt 的组/捆绑节点的优秀示例https://gist.github.com/GerHobbelt/3071239
作为这里的 JSFiddle:
https://jsfiddle.net/NovasTaylor/tco2fkad/
显示展示了可折叠节点和区域(外壳)。
我没有想到的一个调整是如何向扩展节点添加标签。 我已经使用类似于以下内容的代码成功地为我的其他力网络图中的节点添加了标签:
nodes.append("text")
.attr("class", "nodetext")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) {
// d.name is a label for the node, present in the JSON source
return d.name;
});
有没有人足够熟悉 Ger 的例子来指导我朝着正确的方向前进?
在输入时,不是附加circle
而是附加带有circle
和text
的g
。 然后重新考虑一下以修复g
而不是circle
的运动。 最后,仅当节点具有名称(意味着它是叶子)时才追加写出.text()
):
node = nodeg.selectAll("g.node").data(net.nodes, nodeid);
node.exit().remove();
var onEnter = node.enter();
var g = onEnter
.append("g")
.attr("class", function(d) { return "node" + (d.size?"":" leaf"); })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
g.append("circle")
// if (d.size) -- d.size > 0 when d is a group node.
.attr("r", function(d) { return d.size ? d.size + dr : dr+1; })
.style("fill", function(d) { return fill(d.group); })
.on("click", function(d) {
expand[d.group] = !expand[d.group];
init();
});
g.append("text")
.attr("fill","black")
.text(function(d,i){
if (d['name']){
return d['name'];
}
});
并重构刻度线以使用g
而不是 circle:
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
更新了小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.