NetworkX is a Python library for creating, manipulating, and analyzing complex networks of nodes and edges. It supports multiple graph types (directed, undirected, weighted, multi-edge), provides implementations of over 100 graph algorithms, and integrates seamlessly with scientific Python tools like NumPy, SciPy, and Matplotlib. The library's key strength is its practical API design: graphs are Python objects, nodes can be any hashable type, and edge/node attributes are stored as dictionaries, making NetworkX both powerful for research and accessible for rapid prototyping. One critical insight: NetworkX prioritizes readability and ease of use over raw performance—for massive graphs exceeding millions of edges, consider graph-specific libraries like graph-tool or dedicated GPU-accelerated frameworks.
What This Cheat Sheet Covers
This topic spans 28 focused tables and 178 indexed concepts. Below is a complete table-by-table outline of this topic, spanning foundational concepts through advanced details.
Table 1: Graph Types and Creation
| Type | Example | Description |
|---|---|---|
G = nx.Graph()G.add_edges_from([(1,2), (2,3)]) | Undirected graph where edges have no direction; allows self-loops but not parallel edges between same node pair. | |
G = nx.DiGraph()G.add_edge(1, 2) | Directed graph where edges have direction (u→v distinct from v→u); supports self-loops. | |
G = nx.MultiGraph()G.add_edge(1, 2, weight=1.5)G.add_edge(1, 2, weight=2.0) | Undirected graph allowing multiple edges (parallel edges) between same node pair; each edge can hold distinct attributes. | |
G = nx.MultiDiGraph()G.add_edge('A', 'B', key=0)G.add_edge('A', 'B', key=1) | Directed graph supporting multiple directed edges between same node pair; useful for modeling transport networks with multiple routes. | |
G.add_node(5, color='red') | Adds single node with optional key-value attributes. |