I am trying to plot graphs using the package networkx
.
In my graphs, I know which node is the root node and which nodes are the terminal nodes.
I want my graph to be vertically constructed and want to place the root node at the top of my graph. Accordingly, I want to place the terminal nodes to the bottom. Regardless of the edges of the graph, I want this to be held at any figure plotted. The nodes in between can arbitrarily (but in vertical direction depending on their rank) be placed.
To list several examples on the internet: I checked the tutorials on networkx from its official site and from
this site.
I also saw some SO questions like
this,
this
and
this.
They helped me to a certain extend, but I couldn't get what I actually wanted.
I also checked the PyGraphwiz
to learn whether such a node arrangement can be achieved by creating a '.dot'
file but I couldn't make any progress.
The graph I plot and its code is given below. As can be seen, there isn't any line or mark defining which node is the root node and which ones are the terminals.
import networkx as nx
import matplotlib.pyplot as plt
graph = [('O', 'A'), ('O', 'C'), ('O', 'E'), ('O', 'G'), ('O', 'H'),
('A', 'B'), ('A', 'O'),
('B', 'A'),
('C', 'D'), ('C', 'E'), ('C', 'F'), ('C', 'O'),
('D', 'E'), ('D', 'C'), ('D', 'F'),
('E', 'C'), ('E', 'D'), ('E', 'F'), ('E', 'O'),
('F', 'C'), ('F', 'D'), ('F', 'E'),
('G', 'H'), ('G', 'O'),
('H', 'G'), ('H', 'O')]
root_node = 'O'
terminal_nodes = ['B', 'D', 'F', 'H']
G=nx.DiGraph()
for edge in graph:
G.add_edge(edge[0], edge[1])
pos=nx.graphviz_layout(G,prog='dot')
nx.draw(G, pos, arrows=False)
plt.show()