Master NetworkX: Install, Build Weighted Graphs, and Find Shortest Paths in Python
This guide walks you through installing NetworkX, creating weighted undirected graphs, visualizing them with various layouts, computing shortest paths using Dijkstra, and generating minimum spanning trees, all with clear Python code examples.
NetworkX is a Python library for graph theory and complex network modeling, providing built‑in algorithms for analysis, simulation, and visualization.
1. Installing and Importing NetworkX
Install via pip:
<code>pip install networkx</code>If using Anaconda, the library is already available and is typically imported as nx :
<code>import networkx as nx</code>Commonly used functions include creating graphs, adding nodes or edges, and computing shortest paths.
Graph() : create an undirected graph
Graph(A) : create an undirected graph from adjacency matrix A
DiGraph() : create a directed graph
DiGraph(A) : create a directed graph from adjacency matrix A
MultiGraph() : create a multigraph
MultiDiGraph() : create a multidigraph
add_edge() : add a single edge
add_edges_from(List) : add multiple edges from a list
add_node() : add a single node
add_nodes_from(List) : add a collection of nodes
dijkstra_path(G, source, target, weight='weight') : compute the shortest path
dijkstra_path_length(G, source, target, weight='weight') : compute the shortest distance
2. Building a Weighted Undirected Graph
Define a weighted adjacency matrix (zero indicates no direct connection) and convert it to a NetworkX graph:
<code>import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
a = np.array([[0.,9.,2.,4.,7.],
[9.,0.,3.,4.,0.],
[2.,3.,0.,8.,4.],
[4.,4.,8.,0.,6.],
[7.,0.,4.,6.,0.]])
a1 = pd.DataFrame(a, index=range(1,6), columns=range(1,6))
G = nx.from_numpy_array(a1)
G.edges(data=True) # show weights
</code>Draw the graph with edge weights:
<code>pos = nx.shell_layout(G) # layout
nx.draw_networkx(G, pos, node_size=260)
w = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, font_size=12, edge_labels=w)
plt.savefig('images/net0102.png')
plt.show()
</code>Five layout options are available: circular_layout , random_layout , shell_layout , spring_layout (Fruchterman‑Reingold), and spectral_layout .
3. Finding Shortest Paths
NetworkX provides several shortest‑path algorithms such as Dijkstra and Floyd. Example using Dijkstra:
<code>nx.shortest_path(G, 5, 2, weight='weight')
# returns [5, 3, 2]
nx.shortest_path_length(G, 5, 2, weight='weight')
# returns 7
</code>4. Computing a Minimum Spanning Tree
Both Kruskal and Prim algorithms are available via minimum_spanning_tree :
<code>tree_min = nx.minimum_spanning_tree(G, weight='weight')
pos = nx.shell_layout(G)
nx.draw_networkx(tree_min, pos, node_size=260)
w = nx.get_edge_attributes(tree_min, 'weight')
nx.draw_networkx_edge_labels(tree_min, pos, font_size=12, edge_labels=w)
plt.savefig('images/net0103.png')
plt.show()
</code>Reference
Python数学实验与建模 / 司守奎, 孙玺菁, 科学出版社
Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.