2

I'm working with D3 as a newcomer and trying to figure out if the following is possible.

I want two collapsable trees, I'm thinking based the gallery example:

I want to draw lines and make associations between their nodes and a 3rd object.

This is a rough mock-up:

mockup

My confusions at this point are:

  • Is it possible to have two tree layouts present?
  • How can I draw lines from the tree layout nodes to some other object outside the layout?
VividD
  • 10,456
  • 6
  • 64
  • 111
Purrell
  • 12,461
  • 16
  • 58
  • 70

1 Answers1

4

Yes, this is entirely possible -- you could even use the same tree layout for both if you wanted to. The fundamental thing to understand is that the tree layout is only a means of getting the coordinates for the nodes; it doesn't have anything to do with actually drawing them. So you first run the tree layout to get those coordinates and then draw the nodes in a separate step.

In the example you've linked to, the layout is computed at the start of the update function:

// Compute the flattened node list. TODO use d3.layout.hierarchy.
var nodes = tree.nodes(root);

// Compute the "layout".
nodes.forEach(function(n, i) {
  n.x = i * barHeight;
});

The rest of that function is only concerned with actually drawing the nodes and links. So in order to have several trees, you would run the above code again for a different root. This gives you coordinates for both trees which you can then append to container elements that are offset from each other:

var tree1 = svg.append("g");
var tree2 = svg.append("g").attr("transform", "translate(500,0)");

Note that you don't need to change the coordinates of the nodes at all, as they will be relative to their containers. Then you can draw your center element and the links going to it. The only caveat there is that for links starting at the right tree, you would have to offset the coordinates you get from the tree layout by the amount the container element is offset.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204