Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

javascript - D3js Force Directed Graph Link not found

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...