[英]How can I get d3 to display my text labels?
按照此处的示例,我正在使用d3制作力导向图。 这是我到目前为止的内容:
var width = 600,
height = 600;
var svg = d3.select('#d3container')
.append('svg')
.attr('width', width)
.attr('height', height);
// draw the graph nodes
var node = svg.selectAll("circle.node")
.data(mydata.nodes)
.enter()
.append("circle")
.attr("class", "node")
.style("fill", "red")
.attr("r", 12);
node.append("text")
.attr("dx", 9)
.attr("dy", ".35em")
.text(function(d) {
return d.label
});
// draw the graph edges
var link = svg.selectAll("line.link")
.data(mydata.links)
.enter().append("line")
.style('stroke', 'black')
.style("stroke-width", function(d) {
return (d.strength / 75);
});
// create the layout
var force = d3.layout.force()
.charge(-220)
.linkDistance(90)
.size([width, height])
.nodes(mydata.nodes)
.links(mydata.links)
.start();
// define what to do one each tick of the animation
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;
});
//node.attr("cx", function(d) { return d.x; })
//.attr("cy", function(d) { return d.y; });
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
// bind the drag interaction to the nodes
node.call(force.drag);
这将正确选择我的d.label
并将<text>
附加到包含正确文本标签的节点(svg圆)上。 按照示例,我的CSS是:
.node text {
pointer-events: none;
font: 10px sans-serif;
}
但是文本标签不会显示。 我在这里做错了什么?
请注意,对于以下答案,我假设您的数据与示例不同,并且您具有label
属性(示例中为名称)。
也就是说,您正在生成无效的SVG。 您不能在一个带有子text
的circle
,需要将它们包裹在g
:
// draw the graph nodes
var node = svg.selectAll("circle.node")
.data(mydata.nodes)
.enter()
.append("g");
node.append("circle")
.attr("class", "node")
.style("fill", "red")
.attr("r", 12);
node.append("text")
.attr("dx", 9)
.attr("dy", ".35em")
.text(function(d) {
return d.label;
});
这里的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.