pythonnetworkxgraph-theorygraphvizpydot

How to choose root node in "dot" graph layout for plotting with networkx and pydot/pygraphviz


I'm trying to create a visualization for a tree graph using networkx.
How can I choose the root node? i.e. the first one from the top.
Running this code:

import networkx as nx
import pydot
import matplotlib.pyplot as plt
from networkx.drawing.nx_pydot import *

G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(2,4)
G.add_edge(4,5)
G.add_edge(4,6)
G.add_edge(5,7)

pos = pydot_layout(G, prog="dot", root=4)
nx.draw(G, pos, with_labels=True)
plt.show()

Gives this output:

output

Note that I used root=4 to create the layout but still the root in the picture is node 1.
How can I decide which node is chosen as first/top one?
With other prog options such as "twopi" it does react to what I set as root.


Solution

  • I found a solution if G is a tree. Create an auxiliary (directed / nx.DiGraph) graph where the direction of each edge (v,w) is determined by the order in wich v and w are explored in a BFS starting at the root.
    Then get the layout pos out of the directed graph aux_G and plot G with it

    aux_G = my_func_directed_bfs(G, root=4)
    
    pos = pydot_layout(aux_G , prog="dot")
    nx.draw(G, pos, with_labels=True)
    plt.show()