我们正在尝试连接节点,但无法正常工作。节点显示为蜂鸣,但未显示其连接(链接)。
这是我们的代码:
CreateNodesAndLinks() {
let canvas = d3.select(this.refs.anchor)
let width = 800
let height = 600
let companyNodes = Object.values(this.state.data.CompanyNodes)
let links = Object.values(this.state.data.Links)
companyNodes = this.filter_array_values(companyNodes)
links = this.filter_array_values(links)
console.log(companyNodes)
console.log(links)
const simulation = d3.forceSimulation(companyNodes)
.force("link", d3.forceLink(links))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
const svg = canvas.append("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", item => Math.sqrt(item.percent_share));
const companyNode = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(companyNodes)
.join("circle")
.attr("r", 5)
.attr("fill", "black")
.call(this.drag(simulation));
companyNode.append("title")
.text(item => item.company_id);
simulation.on("tick", () => {
link
.attr("x1", d => d.from_id.x)
.attr("y1", d => d.from_id.y)
.attr("x2", d => d.to_id.x)
.attr("y2", d => d.to_id.y);
companyNode
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});
return svg.node();
}
渲染功能:
render() {
return (
<div>
<g ref="anchor" />
</div>
);
}
这就是我们的companyNodes和links Object的样子:https://ibb.co/b5bsRLg
因此连接是在“ from_id”和“ to_id”之间
我们不知道我们在做什么错。也许有人可以帮忙
可能有问题
simulation.on("tick", () => {
link...
方法,但我们无法弄清楚。
答案 0 :(得分:0)
我们发现了错误,也许可以对某人有所帮助。
这个...
const simulation = d3.forceSimulation(companyNodes)
.force("link", d3.forceLink(links))
...必须更改为此:
const simulation = d3.forceSimulation(companyNodes)
.force("link", d3.forceLink(links).id(d => d.company_id)) //company_id is the identifier for one specific company we have in companyNodes
另一件事是,我们不得不将每个from_id
重命名为source
,并将to_id
重命名为target
,因为似乎d3
仅在source
和target