0
我使用了这里的网络图例如: https://bl.ocks.org/mbostock/4062045如何添加文本到力向图中D3.js
我想添加文本元素到节点,但似乎无法得到它出现在节点旁边。
我试着在下面的函数中添加下面几行,但是这样做是为了在屏幕左上角显示文本 - 我期望它出现在左上角。
不确定是否有人可以帮忙?
var textElements = svg.append("g")
.selectAll('text')
.data(graph.nodes)
.enter().append('text').attr('font-size', 15)
.attr('dx', 15)
.attr('dy', 4)
.text(function(d) { return d.id; });
原文:
d3.json("miserables.json", function(error, graph) {
if (error) throw error;
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", function(d) { return color(d.group); })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
node.append("title")
.text(function(d) { return d.id; });
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
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; });
}
});