I tried setting both nodes and links at the same time this way:
var force = d3.layout.force()
.size([w, h])
.nodes(nodes)
.links(connections)
In addition to the answers mentioning the null in the source/target of links, the reason for this could be the assignment of an out-of-range source/target. E.g. you have 10 nodes and you assign the target to be the 11-th indexed node.
I've had this issue pop up in a number of ways. Most recently, I had my edge list as follows:
{Source: 0; Target: 1}
instead of:
{source: 0, target: 1}
The force-directed layout uses edge weights to calculate the layout. Try adding a dummy "weight":1
to all of your connections.
The code that initializes the links looks like this:
links.forEach(function(d) {
if (typeof d.source == "number") { d.source = nodes[d.source]; }
if (typeof d.target == "number") { d.target = nodes[d.target]; }
});
Presumably you could tweak that (in the d3 source) to use any property/type.
I think you might have null values in your source and target. I had this bug too and fixed it by filtering out the null values.
I encounter same problem before, it is due to there is null values in source/target of links. print out nodes and links information might help to debug
Thanks to the answers above which refer to null source or target values!
I've been testing out the graph from http://bl.ocks.org/mbostock/4062045, and found that my data referenced a missing node.
This may help others debug this issue:
d3.json("my-buggy-data.json", function(error, graph) {
// Find blank links, which give the error
// "Uncaught TypeError: Cannot read property 'weight' of undefined"
graph.links.forEach(function(link, index, list) {
if (typeof graph.nodes[link.source] === 'undefined') {
console.log('undefined source', link);
}
if (typeof graph.nodes[link.target] === 'undefined') {
console.log('undefined target', link);
}
});
force
.nodes(graph.nodes)
.links(graph.links)
.start();