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
Everything in NetworkX starts with choosing the right graph class, and that choice locks in two decisions: whether edges have direction, and whether parallel edges between the same pair are allowed. Plain Graph and DiGraph cover most work; the Multi variants exist for when two nodes can be joined by several distinct edges, like multiple flights between two cities. The rest of the table is how you populate one—adding nodes and edges singly or in bulk, with add_edge conveniently creating any missing endpoints for you.
| 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. |