Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. Supports various graph types (Directed, Undirected, Multigraphs) and features a vast library of standard graph algorithms. Use for network analysis, graph theory, social network analysis, biological networks, infrastructure networks, path finding, centrality measures, community detection, graph algorithms, shortest paths, PageRank, connectivity analysis, and routing optimization.
Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. Supports various graph types (Directed, Undirected, Multigraphs) and features a vast library of standard graph algorithms. Use for network analysis, graph theory, social network analysis, biological networks, infrastructure networks, path finding, centrality measures, community detection, graph algorithms, shortest paths, PageRank, connectivity analysis, and routing optimization.
version
3.2
license
BSD-3-Clause
NetworkX - Network Analysis and Graph Theory
NetworkX is the go-to library for analyzing complex networks. It treats graphs as flexible containers for nodes (any hashable object) and edges, which can carry arbitrary metadata.
When to Use
Analyzing social, biological, or infrastructure networks.
import networkx as nx
# ❌ BAD: Manual neighbor iteration for degree calculation
count = 0for n in G.nodes():
for neighbor in G.neighbors(n):
count += 1# ✅ GOOD: Use built-in degree property
degrees = dict(G.degree())
# ❌ BAD: Re-calculating shortest paths in a loopfor target in targets:
path = nx.dijkstra_path(G, source, target) # Re-scans graph every time# ✅ GOOD: Calculate single-source shortest paths once
paths = nx.single_source_dijkstra_path(G, source)
# 'paths' now contains the shortest path to every reachable node# ❌ BAD: Using lists for edges in large graphs# (Creating a graph from a massive edge list one by one is slow)# ✅ GOOD: Bulk loading
G.add_edges_from(edge_list)
deffind_route(G, start, end, max_load):
"""Find shortest path that respects a capacity constraint."""# Filter edges by capacity
view = nx.subgraph_view(G, filter_edge=lambda u, v: G[u][v]['capacity'] >= max_load)
ifnot nx.has_path(view, start, end):
returnNonereturn nx.shortest_path(view, start, end, weight='distance')
3. Visualizing Hierarchical Structures
defplot_tree(G, root):
"""Custom layout for tree-like structures."""
pos = nx.spring_layout(G) # Basic layout# Or use graphviz for better tree layouts# pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
plt.figure(figsize=(12, 8))
nx.draw(G, pos, with_labels=True, node_color='lightblue',
node_size=500, font_size=10, arrowsize=20)
plt.show()
Performance Optimization
Using Graph Views
Instead of creating copies of the graph when filtering nodes/edges, use a "view" which is O(1) in time and memory.
# Create a view of the graph with only heavy edges
heavy_edges = nx.subgraph_view(G, filter_edge=lambda u, v: G[u][v]['weight'] > 10)
Efficient Node Access
When iterating over nodes and their attributes, use data=True.
# Faster than calling G.nodes[n] inside the loopfor n, attrs in G.nodes(data=True):
if attrs.get('type') == 'target':
do_something(n)
Common Pitfalls and Solutions
Dictionary modification during iteration
# ❌ Problem: Changing the graph while looping over nodesfor n in G.nodes():
if G.degree(n) == 0:
G.remove_node(n) # Error!# ✅ Solution: Convert nodes to a list firstfor n inlist(G.nodes()):
if G.degree(n) == 0:
G.remove_node(n)
Self-loops and Multi-edges in simple Graphs
# ❌ Problem: Adding a second edge between A and B in nx.Graph()
G.add_edge("A", "B", weight=10)
G.add_edge("A", "B", weight=20) # Overwrites the first weight!# ✅ Solution: Use MultiGraph if multiple relations exist
MG = nx.MultiGraph()
MG.add_edge("A", "B", weight=10)
MG.add_edge("A", "B", weight=20) # Both are preserved
Directionality in flow algorithms
# ❌ Problem: Running PageRank on an Undirected graph# It works, but it's just a scaled degree centrality.# ✅ Solution: Ensure you use DiGraph for influence metrics
DG = nx.DiGraph(G) # Converts undirected to directed with symmetric edges
NetworkX provides the perfect balance between ease of use and algorithmic depth. Whether you are solving a small logic puzzle or analyzing a complex biological system, it provides the tools to understand the underlying structure of your data.