6
$\begingroup$

I've got a tree graph and I would like to have a specific node be the root in the laid-out Graph as well. Here's a MWE:

g = 
 TreeGraph[
  {1 -> 2, 1 -> 3, 2 -> 4, 2 -> 5, 2 -> 7, 7 -> 8, 2 -> 9, 3 -> 6},
  VertexLabels -> Automatic
  ]

bad graph

I want, e.g. 1 to be the top-most node without having to compute vertex coordinates myself.

Is this possible?

$\endgroup$
  • 1
    $\begingroup$ Or use "LayeredDigraphEmbedding", which will automatically find the source in a directed graph. The result will be different. $\endgroup$ – Szabolcs Oct 21 '18 at 9:33
  • $\begingroup$ @Szabolcs I actually have an undirected graph, but that is good to know if I decided to switch things up to directed graphs $\endgroup$ – b3m2a1 Oct 21 '18 at 19:14
  • 1
    $\begingroup$ There's also IGLayoutReingoldTilford in IGraph/M with the "RootVertices" option. i.stack.imgur.com/NiUQr.png "RootVertices" must be a list to support forests (not just trees). $\endgroup$ – Szabolcs Oct 21 '18 at 19:19
  • $\begingroup$ @Szabolcs off-topic, but do you know a method to make the layout extend more if the number of leaves for the root (381) is much greater than the depth (~5)? Right now it just flattens out and I'd like to be able to see the structure better. $\endgroup$ – b3m2a1 Oct 21 '18 at 19:22
  • 1
    $\begingroup$ The GraphLayout doc page describes lots fo sub-options, which you should look at. LayeredEmbedding has LeafDistance and LayerSizeFunction for horizontal and vertical scaling, effectively. The IGraph/M equivalent has similar. $\endgroup$ – Szabolcs Oct 21 '18 at 19:26
4
$\begingroup$
TreeGraph[{1 -> 2, 1 -> 3, 2 -> 4, 2 -> 5, 2 -> 7, 7 -> 8, 2 -> 9, 
  3 -> 6}, VertexLabels -> "Name", GraphLayout -> {"LayeredEmbedding", "RootVertex" -> 1}]

Alternatively, use the vertex list with the desired order as the first argument:

TreeGraph[Range[9], {1 -> 2, 1 -> 3, 2 -> 4, 2 -> 5, 2 -> 7, 7 -> 8, 2 -> 9, 3 -> 6},
 VertexLabels -> "Name"]

enter image description here

Also TreePlot with its optional third and second arguments to specify the root vertex and its position:

TreePlot[{1 -> 2, 1 -> 3, 2 -> 4, 2 -> 5, 2 -> 7, 7 -> 8, 2 -> 9, 3 -> 6}, Top, 1,
  VertexLabeling -> True]

enter image description here

$\endgroup$
  • $\begingroup$ Wonderful. "RootVertex" is what I needed. $\endgroup$ – b3m2a1 Oct 20 '18 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.