modifying the d3 force-directed graph example modifying the d3 force-directed graph example json json

modifying the d3 force-directed graph example


This link links to a working example based on the your example.

The critical code is placed just before initialization of force layout:

var nodeMap = {};graph.nodes.forEach(function(d) { nodeMap[d.name] = d; });graph.links.forEach(function(l) {    l.source = nodeMap[l.source];    l.target = nodeMap[l.target];})force.nodes(graph.nodes)    .links(graph.links)    .start();

That way you will be able to use your data format in the same fashion as the original format is used (and many examples on the net follow that original format, so you will be able to adapt many of them to your format without problems).

(json file is not used in my example, due to restrictions of jsfiddle; instead, function getData() is made to return the data; but this is not essential to your question; you can use this solution with json files too)

Hope this helps.


D3 provides two ways of specifying link source and target for the force layout. The first, used in the example you've linked to, is to provide the index of the node in the array of nodes. When the force layout is started, this is replaced with the reference to the actual node. The second is to provide the reference to the actual node explicitly.

To reference a node by name, you need something that allows you to resolve that reference. For example:

var nodeMap = {};graph.nodes.forEach(function(d) { nodeMap[d.name] = d; });

Then you can do

graph.links.forEach(function(l) {  l.source = nodeMap[l.source];  l.target = nodeMap[l.target];})

You can of course also use this to define links to start with:

"links":[ {"source":nodeMap["stkbl0001"],"target":nodeMap["stkbl0005"],"value":3}]