0
# Graph Classes
1
2
Core graph data structures that form the foundation of NetworkX. These classes support different types of networks with flexible node and edge attribute storage.
3
4
## Capabilities
5
6
### Undirected Graph
7
8
Base class for undirected graphs. Supports self-loops but not multiple edges between the same nodes.
9
10
```python { .api }
11
class Graph:
12
def __init__(self, incoming_graph_data=None, **attr):
13
"""
14
Initialize a graph with optional data and attributes.
15
16
Parameters:
17
- incoming_graph_data: Input graph data (edge list, dict of dicts, NetworkX graph, etc.)
18
- **attr: Graph attributes as keyword arguments
19
"""
20
21
# Node operations
22
def add_node(self, node_for_adding, **attr):
23
"""Add a single node with optional attributes."""
24
25
def add_nodes_from(self, nodes_for_adding, **attr):
26
"""Add multiple nodes with optional attributes."""
27
28
def remove_node(self, n):
29
"""Remove node n and all adjacent edges."""
30
31
def remove_nodes_from(self, nodes):
32
"""Remove multiple nodes and all adjacent edges."""
33
34
def has_node(self, n):
35
"""Return True if node n is in the graph."""
36
37
def number_of_nodes(self):
38
"""Return the number of nodes in the graph."""
39
40
# Edge operations
41
def add_edge(self, u_of_edge, v_of_edge, **attr):
42
"""Add an edge between u and v with optional attributes."""
43
44
def add_edges_from(self, ebunch_to_add, **attr):
45
"""Add edges from an iterable of edge tuples."""
46
47
def remove_edge(self, u, v):
48
"""Remove the edge between u and v."""
49
50
def remove_edges_from(self, ebunch):
51
"""Remove edges from an iterable of edge tuples."""
52
53
def has_edge(self, u, v):
54
"""Return True if the edge (u,v) is in the graph."""
55
56
def get_edge_data(self, u, v, default=None):
57
"""Return edge attribute dictionary for edge (u,v)."""
58
59
def number_of_edges(self):
60
"""Return the number of edges in the graph."""
61
62
# Graph properties
63
def nodes(self, data=False, default=None):
64
"""Return a view of the graph nodes."""
65
66
def edges(self, nbunch=None, data=False, default=None):
67
"""Return a view of the graph edges."""
68
69
def neighbors(self, n):
70
"""Return an iterator over neighbors of node n."""
71
72
def degree(self, nbunch=None, weight=None):
73
"""Return degree of nodes."""
74
75
def adjacency(self):
76
"""Return an iterator over (node, adjacency dict) tuples."""
77
78
# Graph operations
79
def copy(self, as_view=False):
80
"""Return a copy of the graph."""
81
82
def clear(self):
83
"""Remove all nodes and edges from the graph."""
84
85
def clear_edges(self):
86
"""Remove all edges from the graph without altering nodes."""
87
88
def update(self, edges=None, nodes=None):
89
"""Update graph using nodes/edges/graphs as input."""
90
91
def size(self, weight=None):
92
"""Return number of edges or sum of edge weights."""
93
94
def subgraph(self, nodes):
95
"""Return a subgraph view containing only specified nodes."""
96
97
def edge_subgraph(self, edges):
98
"""Return edge-induced subgraph view."""
99
100
def to_directed(self, as_view=False):
101
"""Return directed representation of the graph."""
102
103
def to_undirected(self, as_view=False):
104
"""Return undirected representation of the graph."""
105
106
def is_multigraph(self):
107
"""Return True if graph is a multigraph."""
108
109
def is_directed(self):
110
"""Return True if graph is directed."""
111
112
def order(self):
113
"""Return number of nodes (same as number_of_nodes)."""
114
```
115
116
### Directed Graph
117
118
Directed graph class that extends Graph with support for directed edges and in/out degree operations.
119
120
```python { .api }
121
class DiGraph(Graph):
122
"""Directed graph class supporting directed edges."""
123
124
# Directed-specific degree methods
125
def in_degree(self, nbunch=None, weight=None):
126
"""Return in-degree of nodes."""
127
128
def out_degree(self, nbunch=None, weight=None):
129
"""Return out-degree of nodes."""
130
131
# Directed neighbors
132
def predecessors(self, n):
133
"""Return an iterator over predecessor nodes of n."""
134
135
def successors(self, n):
136
"""Return an iterator over successor nodes of n."""
137
138
# Directed graph operations
139
def reverse(self, copy=True):
140
"""Return the reverse of the graph."""
141
142
def to_undirected(self, reciprocal=False, as_view=False):
143
"""Return an undirected representation of the digraph."""
144
```
145
146
### Undirected MultiGraph
147
148
Undirected graph that allows multiple edges between any pair of nodes.
149
150
```python { .api }
151
class MultiGraph(Graph):
152
"""Undirected multigraph supporting multiple edges."""
153
154
# Multi-edge operations
155
def add_edge(self, u_of_edge, v_of_edge, key=None, **attr):
156
"""Add an edge with optional key and attributes."""
157
158
def remove_edge(self, u, v, key=None):
159
"""Remove an edge by key, or arbitrary edge if key not specified."""
160
161
def edges(self, nbunch=None, data=False, keys=False, default=None):
162
"""Return edges with optional keys."""
163
164
def get_edge_data(self, u, v, key=None, default=None):
165
"""Return the attribute dictionary associated with edge (u,v)."""
166
167
def number_of_edges(self, u=None, v=None):
168
"""Return number of edges between u and v."""
169
```
170
171
### Directed MultiGraph
172
173
Directed graph that allows multiple edges between any pair of nodes.
174
175
```python { .api }
176
class MultiDiGraph(DiGraph, MultiGraph):
177
"""Directed multigraph supporting multiple directed edges."""
178
179
# Inherits methods from both DiGraph and MultiGraph
180
def to_undirected(self, reciprocal=False, as_view=False):
181
"""Return an undirected MultiGraph representation."""
182
183
def reverse(self, copy=True):
184
"""Return the reverse of the directed multigraph."""
185
```
186
187
### Graph Views and Filters
188
189
Classes for creating filtered and transformed views of graphs without copying data.
190
191
```python { .api }
192
class SubGraph:
193
"""A view of a subgraph of another graph."""
194
195
class GraphView:
196
"""A read-only view of a graph."""
197
198
class NodeView:
199
"""A view of graph nodes with attribute access."""
200
201
class EdgeView:
202
"""A view of graph edges with attribute access."""
203
204
class DegreeView:
205
"""A view of node degrees."""
206
```
207
208
## Usage Examples
209
210
### Creating Different Graph Types
211
212
```python
213
import networkx as nx
214
215
# Undirected graph
216
G = nx.Graph()
217
G.add_edges_from([(1, 2), (2, 3), (3, 1)])
218
219
# Directed graph
220
DG = nx.DiGraph()
221
DG.add_edges_from([(1, 2), (2, 3), (3, 1)])
222
223
# Multigraph (allows multiple edges)
224
MG = nx.MultiGraph()
225
MG.add_edge(1, 2, key='first')
226
MG.add_edge(1, 2, key='second') # Second edge between same nodes
227
228
# Directed multigraph
229
MDG = nx.MultiDiGraph()
230
MDG.add_edge(1, 2, key='a', weight=1.5)
231
MDG.add_edge(1, 2, key='b', weight=2.0)
232
```
233
234
### Node and Edge Attributes
235
236
```python
237
G = nx.Graph()
238
239
# Add nodes with attributes
240
G.add_node(1, name='Alice', age=25)
241
G.add_node(2, name='Bob', age=30)
242
243
# Add edges with attributes
244
G.add_edge(1, 2, weight=0.8, relationship='friend')
245
246
# Access attributes
247
print(G.nodes[1]['name']) # 'Alice'
248
print(G.edges[1, 2]['weight']) # 0.8
249
```
250
251
### Graph Operations
252
253
```python
254
G = nx.complete_graph(5)
255
256
# Basic properties
257
print(f"Nodes: {G.number_of_nodes()}")
258
print(f"Edges: {G.number_of_edges()}")
259
print(f"Density: {nx.density(G)}")
260
261
# Node operations
262
neighbors = list(G.neighbors(0))
263
degree = G.degree(0)
264
265
# Subgraph
266
subgraph = G.subgraph([0, 1, 2])
267
268
# Copy
269
G_copy = G.copy()
270
```