fccoelho
fccoelho

Reputation: 6204

Converting nodes and links to hierarchical tree in d3.js

I have a JSON representing a graph (also in my case a tree) whi lookx like this:

{"directed": true, "graph": [], 
"nodes": [{"time": 4, "id": 4551308, "name": "Alto da Boa Vista"}, {"time": 7, "id": 4551309, "name": "Sumare"},
...
"links": [{"source": 0, "target": 36, "weight": 1}, 
{"source": 1, "target": 36, "weight": 1},
...

In order to use it to build a tree like in this example, http://mbostock.github.com/d3/talk/20111116/force-collapsible.html, I need to convert this JSON in a hierarchical object with children nodes nested within the parents as illustrated here: https://github.com/mbostock/d3/wiki/Tree-Layout#wiki-tree.

Does D3 have some built-in function to convert from graph to tree? or how would you go about generating a nested tree JSON objetc from graph?

I have the example in this jsFiddle: http://jsfiddle.net/fccoelho/bFT8K/8/

Upvotes: 4

Views: 3560

Answers (1)

Stephen Young
Stephen Young

Reputation: 96

Ok, this is a 2 part answer.

Part 1: D3 does have built in functionality to turn arrays into nested structures. Have a look at the d3.nest() function

This is mostly meant for hierarchical layouts: Cluster, Pack, Partition, Treemap

Part 2: If you are trying to achieve a layout similar to the example you posted then you don't need to do anything to your data. That example uses a force layout which expects a graph. Since the force layout can handle a graph of any shape and a tree is just a graph that adheres to a few constraints you don't need to do any conversion. If the shape of your graph happens to be a tree it will look like a tree.

This should be good enough:

force
  .nodes(spread.nodes)
  .links(spread.links)
  .start();

Upvotes: 4

Related Questions