我的 force layout 代码是标准的,基于通常的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();
}
我尝试向每个节点添加标签。请注意上面的标签代码。这会将标签添加到节点元素(由浏览器控制台确认),但标签不会出现:
由于D3不支持z-index,因此添加元素的顺序显然是错误的。如何让标 checkout 现在每个节点上?
最佳答案
Here是更新后的 Observable。
问题在于您要在圆
“内部”添加文本,而这在 SVG 中是不可能的。解决方案是创建一个 group
而不是一个 circle
,使用 translate
而不是 cx
和 cy
在 tick
函数中,最后在 group
内创建圆
和文本
。我希望它有帮助。
关于javascript - D3.js 可观察力布局,标签未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57172926/