Python NetworkX Module
NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks (graphs).
Installation
pip install networkx
Creating a Graph
import networkx as nx
# Create an empty graph with no nodes and no edges
G = nx.Graph()
Adding Nodes and Edges
# Add a single node
G.add_node(1)
# Add a list of nodes
G.add_nodes_from([2, 3])
# Add an edge between 1 and 2
G.add_edge(1, 2)
# Add a list of edges
G.add_edges_from([(1, 3), (2, 3)])
Analyzing the Graph
print(f"Number of nodes: {G.number_of_nodes()}")
print(f"Number of edges: {G.number_of_edges()}")
# Check degrees (number of connections)
print(f"Degree of node 1: {G.degree[1]}")
# Shortest path
print(nx.shortest_path(G, source=1, target=3))
Directed Graphs
Use DiGraph for directed edges (A -> B is different from B -> A).
DG = nx.DiGraph()
DG.add_edge(1, 2) # 1 -> 2
DG.add_edge(2, 1) # 2 -> 1
Drawing Graphs
NetworkX works with Matplotlib to draw graphs.
import matplotlib.pyplot as plt
nx.draw(G, with_labels=True, font_weight='bold')
plt.show()
Algorithms
NetworkX contains many standard graph algorithms.
# PageRank
pr = nx.pagerank(G)
# Connected Components
components = list(nx.connected_components(G))
# Clustering Coefficient
clustering = nx.clustering(G)