Python package for creating and manipulating graphs and networks
npx @tessl/cli install tessl/pypi-networkx@2.8.00
# NetworkX
1
2
A comprehensive Python library for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks and graphs. NetworkX provides extensive algorithms for graph analysis including shortest paths, centrality measures, clustering, connectivity analysis, and community detection.
3
4
## Package Information
5
6
- **Package Name**: networkx
7
- **Language**: Python
8
- **Installation**: `pip install networkx`
9
10
## Core Imports
11
12
```python
13
import networkx as nx
14
```
15
16
Common for specific functionality:
17
18
```python
19
from networkx import Graph, DiGraph, MultiGraph, MultiDiGraph
20
from networkx.algorithms import shortest_path, betweenness_centrality
21
from networkx.generators import complete_graph, random_graph
22
```
23
24
## Basic Usage
25
26
```python
27
import networkx as nx
28
import matplotlib.pyplot as plt
29
30
# Create a simple graph
31
G = nx.Graph()
32
33
# Add nodes
34
G.add_node(1)
35
G.add_nodes_from([2, 3, 4])
36
37
# Add edges
38
G.add_edge(1, 2)
39
G.add_edges_from([(2, 3), (3, 4), (4, 1)])
40
41
# Basic graph properties
42
print(f"Number of nodes: {G.number_of_nodes()}")
43
print(f"Number of edges: {G.number_of_edges()}")
44
print(f"Nodes: {list(G.nodes())}")
45
print(f"Edges: {list(G.edges())}")
46
47
# Compute shortest path
48
path = nx.shortest_path(G, source=1, target=3)
49
print(f"Shortest path from 1 to 3: {path}")
50
51
# Compute centrality
52
centrality = nx.betweenness_centrality(G)
53
print(f"Betweenness centrality: {centrality}")
54
55
# Draw the graph
56
nx.draw(G, with_labels=True, node_color='lightblue',
57
node_size=500, font_size=16, font_weight='bold')
58
plt.show()
59
```
60
61
## Architecture
62
63
NetworkX provides a flexible graph data structure and extensive algorithm library:
64
65
- **Graph Classes**: Core graph types (Graph, DiGraph, MultiGraph, MultiDiGraph) supporting various node/edge attributes
66
- **Algorithm Modules**: Comprehensive collection of graph algorithms organized by functionality
67
- **Generators**: Functions to create various types of graphs (random, structured, classic)
68
- **I/O Modules**: Support for reading/writing graphs in multiple formats
69
- **Drawing**: Integration with matplotlib and other visualization libraries
70
71
The library is designed for maximum reusability across network analysis applications, research projects, and educational purposes.
72
73
## Capabilities
74
75
### Graph Classes
76
77
Core graph data structures supporting different types of networks: undirected graphs, directed graphs, and multigraphs with flexible node and edge attribute storage.
78
79
```python { .api }
80
class Graph:
81
def __init__(self, incoming_graph_data=None, **attr): ...
82
def add_node(self, node_for_adding, **attr): ...
83
def add_edge(self, u_of_edge, v_of_edge, **attr): ...
84
def number_of_nodes(self): ...
85
def number_of_edges(self): ...
86
87
class DiGraph(Graph):
88
def in_degree(self, nbunch=None, weight=None): ...
89
def out_degree(self, nbunch=None, weight=None): ...
90
def predecessors(self, n): ...
91
def successors(self, n): ...
92
```
93
94
[Graph Classes](./graph-classes.md)
95
96
### Graph Algorithms
97
98
Extensive collection of graph algorithms including shortest paths, centrality measures, connectivity analysis, community detection, and more. Over 100+ algorithms covering all major areas of graph theory.
99
100
```python { .api }
101
def shortest_path(G, source=None, target=None, weight=None, method='dijkstra'): ...
102
def betweenness_centrality(G, k=None, normalized=True, weight=None, endpoints=False, seed=None): ...
103
def connected_components(G): ...
104
def pagerank(G, alpha=0.85, personalization=None, max_iter=100, tol=1e-06, nstart=None, weight='weight', dangling=None): ...
105
```
106
107
[Algorithms](./algorithms.md)
108
109
### Graph Generators
110
111
Functions to create various types of graphs including classic graphs, random graphs, social networks, lattices, trees, and specialized network structures.
112
113
```python { .api }
114
def complete_graph(n, create_using=None): ...
115
def path_graph(n, create_using=None): ...
116
def cycle_graph(n, create_using=None): ...
117
def random_graph(n, p, seed=None, directed=False): ...
118
def barabasi_albert_graph(n, m, seed=None, initial_graph=None): ...
119
```
120
121
[Graph Generators](./generators.md)
122
123
### Graph Conversion
124
125
Functions to convert between NetworkX graphs and other data structures including matrices, pandas DataFrames, dictionaries, and edge lists.
126
127
```python { .api }
128
def to_networkx_graph(data, create_using=None, multigraph_input=False): ...
129
def to_numpy_array(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0): ...
130
def from_pandas_adjacency(df, create_using=None): ...
131
def to_dict_of_dicts(G, nodelist=None, edge_data=None): ...
132
```
133
134
[Graph Conversion](./conversion.md)
135
136
### Graph I/O
137
138
Reading and writing graphs in various formats including adjacency lists, edge lists, GraphML, GML, GEXF, Pajek, and custom formats.
139
140
```python { .api }
141
def read_edgelist(path, comments='#', delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding='utf-8'): ...
142
def write_edgelist(G, path, comments='#', delimiter=' ', data=True, encoding='utf-8'): ...
143
def read_graphml(path, node_type=str, edge_key_type=str, encoding='utf-8'): ...
144
def write_gml(G, path, stringizer=None): ...
145
```
146
147
[Graph I/O](./graph-io.md)
148
149
### Graph Drawing and Visualization
150
151
Graph layout algorithms and drawing functions with matplotlib integration for visualizing networks.
152
153
```python { .api }
154
def draw(G, pos=None, ax=None, **kwds): ...
155
def spring_layout(G, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, weight='weight', scale=1, center=None, dim=2, seed=None): ...
156
def circular_layout(G, scale=1, center=None, dim=2): ...
157
def kamada_kawai_layout(G, dist=None, pos=None, weight='weight', scale=1, center=None, dim=2): ...
158
```
159
160
[Graph Drawing](./drawing.md)
161
162
### Core Utilities
163
164
Essential utility functions for graph manipulation, analysis, and operations. These functions provide fundamental graph operations and property checking capabilities.
165
166
```python { .api }
167
def density(G): ...
168
def degree_histogram(G): ...
169
def freeze(G): ...
170
def is_frozen(G): ...
171
def info(G, n=None): ...
172
def create_empty_copy(G, with_data=True): ...
173
def set_node_attributes(G, values, name=None): ...
174
def get_node_attributes(G, name): ...
175
def set_edge_attributes(G, values, name=None): ...
176
def get_edge_attributes(G, name): ...
177
def is_weighted(G): ...
178
def is_empty(G): ...
179
def nodes_with_selfloops(G): ...
180
def number_of_selfloops(G): ...
181
```
182
183
### Linear Algebra
184
185
Graph matrix operations and spectral analysis including adjacency matrices, Laplacian matrices, and eigenvalue computations.
186
187
```python { .api }
188
def adjacency_matrix(G, nodelist=None, dtype=None, weight='weight'): ...
189
def laplacian_matrix(G, nodelist=None, weight='weight'): ...
190
def adjacency_spectrum(G, weight='weight'): ...
191
def algebraic_connectivity(G, weight='weight', normalized=True, tol=1e-8, method='tracemin_pcg', seed=None): ...
192
```
193
194
[Linear Algebra](./linear-algebra.md)
195
196
## Types
197
198
```python { .api }
199
# Node types
200
NodeType = Any # Any hashable Python object except None
201
202
# Graph attribute types
203
NodeAttr = Dict[str, Any]
204
EdgeAttr = Dict[str, Any]
205
GraphAttr = Dict[str, Any]
206
207
# Data structure types
208
NodeView = Mapping[NodeType, NodeAttr]
209
EdgeView = Mapping[Tuple[NodeType, NodeType], EdgeAttr]
210
DegreeView = Mapping[NodeType, int]
211
212
# Common return types
213
PathType = List[NodeType]
214
ComponentType = Set[NodeType]
215
CentralityDict = Dict[NodeType, float]
216
```