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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With