[英]Nodes and links in D3 (React): How to connect nodes through my links?
We're trying to connect our nodes but it doesn't work.我们正在尝试连接我们的节点,但它不起作用。 The nodes are beeing displayed but not their connections(links).正在显示节点,但不显示它们的连接(链接)。
This is our code:这是我们的代码:
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 function:渲染功能:
render() {
return (
<div>
<g ref="anchor" />
</div>
);
}
And this is how our companyNodes and links Object looks like: https://ibb.co/b5bsRLg这就是我们的公司节点和链接对象的样子: https ://ibb.co/b5bsRLg
So the connection is between "from_id" and "to_id"所以连接在“from_id”和“to_id”之间
And we don't know what we're doing wrong.我们不知道我们做错了什么。 Maybe someone can help也许有人可以帮忙
Probably there's something wrong with the可能有问题
simulation.on("tick", () => {
link...
method but we can't figure it out.方法,但我们无法弄清楚。
We found our mistakes and maybe it could help someone.我们发现了我们的错误,也许它可以帮助别人。
This...这个...
const simulation = d3.forceSimulation(companyNodes)
.force("link", d3.forceLink(links))
...had to be changed to this: ...必须更改为:
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
And the other thing was that we had to rename every from_id
to source
and to_id
to target
because it seems like d3
is only working with source
and target
另一件事是我们必须将每个from_id
重命名为source
并将to_id
重命名为target
因为d3
似乎只与source
和target
一起工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.