[英]D3.js Observable Force Layout, Labels not appearing
My force layout code is standard, based of the usual data : 我的部队布局代码是标准的,基于通常的数据 :
chart = {
const links = data.links.map(d => Object.create(d));
const nodes = data.nodes.map(d => Object.create(d));
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2))
.force("link", d3.forceLink().distance(function(d) {return d.value;}).strength(0.1))
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
const link = svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.join("line")
.attr("stroke-width", d => Math.sqrt(d.id));
const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.attr("class", "labels")
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 10)
.attr("fill", color)
.call(drag(simulation));
var lables = node.append("text")
.text(function(d) {
return d.id;
})
.attr('x', 6)
.attr('y', 3);
node.append("title")
.text(d => d.id);
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});
invalidation.then(() => simulation.stop());
return svg.node();
}
I am trying to add labels to each node. 我正在尝试向每个节点添加标签 。 Note the label code above. 注意上面的标签代码。 This adds the labels to the node element (confirmed by browser console), but the labels do not appear: 这会将标签添加到节点元素(由浏览器控制台确认),但标签不会出现:
Since D3 doesn't support z-index the order of adding elements is obviously wrong. 由于D3不支持z-index,因此添加元素的顺序显然是错误的。 How can I make the labels appear on each node? 如何使标签出现在每个节点上?
Here is the updated Observable. 这是更新的Observable。
The problem was that you were adding the text "inside" the circle
and that is not possible in an SVG. 问题是您要在circle
“内部”添加文本,而这在SVG中是不可能的。 The solution is to create a group
instead of a circle
, use translate
instead cx
and cy
in the tick
function, and finally, create the circle
and the text
inside the group
. 解决方案是创建一个group
而不是一个circle
,在tick
函数中使用translate
代替cx
和cy
,最后在group
创建一个circle
和text
。 I hope it helps. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.