draw graph with edges networkx in python

To draw a graph with edges in NetworkX, you can use the networkx.draw() function. Here's an example:

main.py
import networkx as nx
import matplotlib.pyplot as plt

# create graph
G = nx.DiGraph()

# add edges
G.add_edge('A', 'B', weight=6)
G.add_edge('A', 'C', weight=3)
G.add_edge('B', 'C', weight=2)
G.add_edge('B', 'D', weight=5)
G.add_edge('C', 'D', weight=3)
G.add_edge('A', 'D', weight=1)

# draw graph
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, font_weight='bold')
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

# show graph
plt.show()
507 chars
23 lines

In this example, we first create a directed graph G and then add edges to it. We then specify the position of each node using the spring_layout() function, and use nx.draw() to draw the graph with labels and a bold font. Finally, we use nx.get_edge_attributes() to get the weight of each edge, and nx.draw_networkx_edge_labels() to draw the edge labels.

Note that this example uses Matplotlib to actually show the graph. You may need to install it separately, if you haven't already.

related categories

gistlibby LogSnag