0

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.

graph drawn using the code below


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()
Community
  • 1
  • 1
T-800
  • 1,543
  • 2
  • 17
  • 26

1 Answers1

0

It is the structure definition of the directed graph itself which define all terminal nodes,

Terminal node could change only when you move the root node or when the graph structure/shape definition change.

In your example, considering your graph definition with node 'O' as root, the graph theory implies that only 'F' & 'G' nodes are terminals..

In the other hand, if you finally just wan't to fix/hack the graphical render of your graph:

You may probably try to get the "y position" value of the top bottom terminal node (in your example node 'F'), then force the "y position" of all other nodes that you "considered" as terminal (in your example ['B', 'D', 'F', 'H']) to the same position.

or

You can change the graph layout to spring layout, and force (by specifying at load) the "x-y position" of all your nodes .

Best regards

T-800
  • 1,543
  • 2
  • 17
  • 26
A. STEFANI
  • 6,707
  • 1
  • 23
  • 48