# Force GraphLayout to put specific node at top

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
]

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

Is this possible?

• Or use "LayeredDigraphEmbedding", which will automatically find the source in a directed graph. The result will be different. Oct 21, 2018 at 9:33
• @Szabolcs I actually have an undirected graph, but that is good to know if I decided to switch things up to directed graphs Oct 21, 2018 at 19:14
• 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). Oct 21, 2018 at 19:19
• @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. Oct 21, 2018 at 19:22
• 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. Oct 21, 2018 at 19:26

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"]

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]

• Wonderful. "RootVertex" is what I needed. Oct 20, 2018 at 23:03