找不到D3js强制定向图链接 [英] D3js Force Directed Graph Link not found
问题描述
我目前正在尝试使用d3js v4构建强制图.我有以下节点和链接,实际上很简单
I'm currently trying to build a force directed graph with d3js v4. I have the following nodes and links, actually pretty simple
节点
[
{
"id":"4d2b0275-5bc7-e611-81c4-00155df7ea33"
},{
"id":"b32b0275-5bc7-e611-81c4-00155df7ea33"
}
]
链接
[
{
"source":"4d2b0275-5bc7-e611-81c4-00155df7ea33",
"target":"b32b0275-5bc7-e611-81c4-00155df7ea33"
}
]
我的forceSimulation设置是
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()
它在带有Uncaught Error: missing: 4d2b0275-5bc7-e611-81c4-00155df7ea33
的d3.forceLink(links)上引发错误.
那么既然链接实际上在那儿,为什么会出错呢?
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:
允许将每个链接的源和目标指定为节点数组中从零开始的索引.
allows each link’s source and target to be specified as a zero-based index into the nodes array.
这意味着源和目标由节点的索引定义,如本示例中的API:
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
];
但是,由于要通过节点的id
而不是其数字索引来定义源和目标,因此必须在id()
函数中指定此ID:
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强制定向图链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!