问题描述
我目前正在尝试使用 d3js v4 构建一个力有向图.我有以下节点和链接,其实很简单
节点
[{"id":"4d2b0275-5bc7-e611-81c4-00155df7ea33"},{"id":"b32b0275-5bc7-e611-81c4-00155df7ea33"}]链接
[{"source":"4d2b0275-5bc7-e611-81c4-00155df7ea33",目标":b32b0275-5bc7-e611-81c4-00155df7ea33"}]我的 forceSimulation 设置是
var 模拟 = d3.forceSimulation(nodes).force("充电", d3.forceManyBody()).force("link", d3.forceLink(links).distance(20).strength(1)).force("x", d3.forceX()).force("y", d3.forceY()).停止()
它在 d3.forceLink(links) 上抛出一个错误,其中 Uncaught Error: missing: 4d2b0275-5bc7-e611-81c4-00155df7ea33
.那么为什么会出现这个错误,因为链接实际上就在那里?
在 D3 中,默认 link.id() 访问函数:
允许将每个链接的源和目标指定为节点数组中从零开始的索引.
这意味着源和目标由节点的索引定义,如 API 中的此示例所示:
var links = [{"source": 0, "target": 1},//从第一个节点到第二个{"source": 1, "target": 2}//从第二个节点到第三个节点];
但是,由于您是通过节点的 id
而不是其数字索引来定义源和目标,因此您必须在 id()
功能:
.force("link", d3.forceLink(links).id(函数(d,i){返回 d.id}).距离(20).强度(1))
I'm currently trying to build a force directed graph with d3js v4. I have the following nodes and links, actually pretty simple
nodes
[
{
"id":"4d2b0275-5bc7-e611-81c4-00155df7ea33"
},{
"id":"b32b0275-5bc7-e611-81c4-00155df7ea33"
}
]
links
[
{
"source":"4d2b0275-5bc7-e611-81c4-00155df7ea33",
"target":"b32b0275-5bc7-e611-81c4-00155df7ea33"
}
]
my forceSimulation setup is
var simulation = d3.forceSimulation(nodes)
.force("charge", d3.forceManyBody())
.force("link", d3.forceLink(links).distance(20).strength(1))
.force("x", d3.forceX())
.force("y", d3.forceY())
.stop()
It throws an error on d3.forceLink(links) with Uncaught Error: missing: 4d2b0275-5bc7-e611-81c4-00155df7ea33
.so why is that error since the link is actually there?
In D3, the default link.id() accessor function:
This means that the source and the target are defined by the index of the node, as in this example in the API:
var links = [
{"source": 0, "target": 1}, //from the first node to the second
{"source": 1, "target": 2} //from the second node to the third
];
However, since you're defining the source and the target by the id
of the node, not by its numeric index, you have to specify this id in the id()
function:
.force("link", d3.forceLink(links)
.id(function(d,i) {
return d.id
})
.distance(20)
.strength(1)
)
这篇关于未找到 D3js 强制有向图链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!