Alex Rivera | Logout

d3.js: "Cannot read property 'weight' of undefined" when manually defining both nodes and links for force layout

Asked 2012-07-06T07:46:31.267
20

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)
    .start();

nodes = [{"name":"data_base_id", "kind":"subgenre"},...]
connections = [{"source":"name_of_node", "target":"name_of_other_node"},...]

I have data that may not have connections, so it is necessary to defined the nodes, so that all of the nodes get rendered. And defining the genres is pretty easy. but I get this error;

Cannot read property 'weight' of undefined

And when I comment out .links(connections) the graph renders (juts a bunch of dots scattered throughout...) How do I get the connections / links to cooperate with d3?

I was reading the docs, and apparently the source and target have to be INDEXES of the nodes in the nodes array. Is there anyway to change that? So, I can use the name of a node rather than the index it has in an array?

Edit
Report

1 Answer

13

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.

answered 2012-07-07T14:52:52.030

Your Answer