问题描述
我试图在d3 Force Directed Graph中的节点添加文本标签,似乎有一个问题。
这是我的时,出现了节点标签但节点堆叠在框的左上角,而节点链接很好。此是我付出努力的结果。任何人都可以告诉我我做错了什么?
在圆圈内添加一个文本元素,这将不起作用。您可以在svg元素下添加组,然后在每个组中附加圈子和文字:
//创建svg
var gnodes = svg.selectAll('g.gnode')
.data(graph.nodes)
.enter()
.append('g')
.classed('gnode',true);
//在每个组中添加一个圆
var node = gnodes.append(circle)
.attr(class,node)
.attr(r,5)
.style(fill,function(d){return color(d.group);})
.call(force.drag);
//将标签附加到每个组
var labels = gnodes.append(text)
.text(function(d){return d.name;}) ;
force.on(tick,function(){
//更新链接
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;});
//翻译组
gnodes。 attr(transform,function(d){
return'translate('+ [dx,dy] +')';
});
}
这个策略的一个分支是
I am trying to add text label to nodes in d3 Force Directed Graph, there seems to be an issue.This is my Fiddle:
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 fiddle is the outcome of that effort i put in. Can anyone tell me what am i doing wrong?
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:
// 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
这篇关于在d3节点中强制定向图形中添加文本标签,并在悬停时调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!