Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find links in d3 v4?

Tags:

d3.js

I have used the following code in d3 v3 to find nodes and links for a horizontal tree (top to bottom). Here is how the tree will look like:

var nodes = d3.layout.tree().nodes(jsonData).reverse(); var links = d3.layout.tree().links(nodes);

I'm trying to do the same in d3 v4. The v4 is missing the tree.links(nodes) method where it can accept the nodes.

How can I find the links in d3 v4?

like image 409
wonderful world Avatar asked Dec 11 '16 14:12

wonderful world


1 Answers

I'm just adding this to save myself (and possibly others) time from having to dig the answers out of the demos. I'm new to D3 as well so I'm hoping this is as helpful to others as it was to me.

Use d3.hierarchy() & node.descendants() to get nodes and links.

// Assigns parent, children, height, depth, etc..
var root = d3.hierarchy(jsonData);

// Assigns the x and y coordinates for the nodes.
tree(root);

// Returns array of node objects.
var nodes = root.descendants();

// Returns array of link objects between nodes.
var links = root.descendants().slice(1);
//var links = root.links(); // to get objects with source and target properties.

Can also shorten this down a bit if wanted which still does all of the above.

var root = d3.hierarchy(jsonData),
    nodes = tree(root).descendants(),
    links = nodes.slice(1);

If you need to grab nodes/links within an event. For example on drag start of a node when using a tree diagram (and I'm sure this could be useful elsewhere as well).

var drag = d3.drag()
    .on("start", function dragStart(d) {
        var nodes = d.descendants(),
            links = nodes.slice(1);
    });

Or alternatively use node.links() where each link defines source and target properties.

var drag = d3.drag()
    .on("start", function dragStart(d) {
        var nodes = d.descendants(),
            links = d.links(); 
    });

You would think this would also work in this case but it doesn't (bummer).

var root = d3.hierarchy(jsonData),
    nodes = tree(root).descendants(),
    links = nodes.links(); // <-- only works on a single node, resort to slice(1).
like image 187
Rick Avatar answered Nov 01 '22 12:11

Rick