【问题标题】:D3js Force Directed Graph Link not found未找到 D3js 强制有向图链接
【发布时间】:2017-01-24 14:42:49
【问题描述】:

我目前正在尝试使用 d3js v4 构建一个力有向图。我有以下节点和链接,其实很简单

节点

[
  {
    "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 设置是

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()

它在 d3.forceLink(links) 上使用Uncaught Error: missing: 4d2b0275-5bc7-e611-81c4-00155df7ea33 引发错误。 那么为什么会出现这个错误,因为链接实际上是存在的?

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    在D3中,默认的link.id()访问函数:

    允许将每个链接的源和目标指定为节点数组中从零开始的索引。

    这意味着源和目标是由节点的索引定义的,如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:

    .force("link", d3.forceLink(links)
         .id(function(d,i) {
             return d.id
         })
        .distance(20)
        .strength(1)
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 2019-05-01
      • 2015-03-02
      • 2017-08-16
      • 2018-02-18
      • 2012-09-17
      • 2015-12-04
      相关资源
      最近更新 更多