Rossy Clair
Rossy Clair

Reputation: 195

Draw a directed graph in Python

I have a data table and I want to show it by a directed graph. My table is following:

point,previous_point
"A","-"
"B","-"
"C","A"
"D","B"
"E","C"
"F","C"
"G","D,E"
"H","F,G"

And I need a graph drawn using by the above data. The graph I want is: enter image description here

I have tried with the networkx package. But the result is not good. Someone can help me improve the graph? Besides, I also want to automatically draw with input data like the above table.

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

G.add_edges_from(
[('Start','A'),('Start','B'),
('A','C'),('B','D'),('C','E'),('C','F'),
 ('D','G'),('E','G'),('F','H'),('G','H'),
 ('H','End')])

 nx.draw(G, with_labels=True)
 plt.show()

Upvotes: 2

Views: 2395

Answers (2)

AveragePythonEnjoyer
AveragePythonEnjoyer

Reputation: 1165

You can adjust the layout of your plot like this:

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

G = nx.DiGraph()

G.add_edges_from(
[('Start','A'),('Start','B'),
('A','C'),('B','D'),('C','E'),('C','F'),
('D','G'),('E','G'),('F','H'),('G','H'),
('H','End')])

pos = graphviz_layout(G, prog="dot")
for k,v in pos.items():
    pos[k]=(-v[1],v[0])

nx.draw_networkx_nodes(G,pos = pos, node_shape = 's', node_size = 200, 
                       node_color = 'none', edgecolors='k')
nx.draw_networkx_edges(G,pos = pos, 
                       node_shape = 's', width = 1,  node_size = 200)
nx.draw_networkx_labels(G,pos = pos, font_size = 5)

plt.show()

Result:

Result

If you want to get exactly the result, you have showed above, you may want to generate the positions yourself and pass them to the draw commands.

Upvotes: 3

SultanOrazbayev
SultanOrazbayev

Reputation: 16551

Instead of networkx one could use mermaid. Here's a chart generated online at https://mermaid.live:

graph LR
    A --> C --> E --> G --> H
    C --> F --> H
    B --> D --> G

enter image description here

Of course, there is scope for adjusting it to suit your needs. Once the desired format is found, it should be feasible to use Python to restructure the original table into format suitable for mermaid.

Upvotes: -1

Related Questions