javascript 将文本标签添加到强制有向图中的 d3 节点并在悬停时调整大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18164230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add text label to d3 node in Force directed Graph and resize on hover
提问by Aditya
I am trying to add text label to nodes in d3 Force Directed Graph, there seems to be an issue. This is my Fiddle:
我正在尝试向 d3 Force Directed Graph 中的节点添加文本标签,似乎存在问题。这是我的小提琴:
When I add the node name like this:
当我像这样添加节点名称时:
node.append("text")
.attr("class", "word")
.attr("dy", ".35em")
.text(function(d) {
console.log(d.name);
return d.name;
});
There's no change but the names are getting logged.
没有变化,但名称正在被记录。
When i tried using bounding box, the node labels appeared but the nodes are stacked up on the top-left corner of box while the node links are fine.This fiddleis the outcome of that effort i put in. Can anyone tell me what am i doing wrong?
当我尝试使用边界框时,节点标签出现但节点堆叠在框的左上角而节点链接很好。这个小提琴是我投入的努力的结果。谁能告诉我是什么我做错了吗?
回答by Pablo Navarro
You are adding a text element inside a circle, that won't work. You can add groups under the svg element and then append the circle and a text in each group:
您正在一个圆圈内添加一个文本元素,这是行不通的。您可以在 svg 元素下添加组,然后在每个组中附加圆圈和文本:
// Create the groups under svg
var gnodes = svg.selectAll('g.gnode')
.data(graph.nodes)
.enter()
.append('g')
.classed('gnode', true);
// Add one circle in each group
var node = gnodes.append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
// Append the labels to each group
var labels = gnodes.append("text")
.text(function(d) { return d.name; });
force.on("tick", function() {
// Update the links
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
// Translate the groups
gnodes.attr("transform", function(d) {
return 'translate(' + [d.x, d.y] + ')';
});
});
A fork of your fiddle with this strategy is here
你的这个策略的一个分支在这里