NetworkX is a Python library for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It provides data structures for graphs, digraphs, and multigraphs, along with a wide range of algorithms for network analysis. Its flexibility and ease of use make it a popular choice for researchers and developers working with graph-based data.
Key features of NetworkX include:
1. Graph Types: Supports undirected graphs (Graph), directed graphs (DiGraph), and graphs that allow multiple edges between any pair of nodes (MultiGraph, MultiDiGraph).
2. Node and Edge Attributes: Allows attaching arbitrary data (e.g., weights, labels, timestamps) to nodes and edges, making it suitable for representing rich, real-world networks.
3. Graph Creation and Manipulation: Provides simple methods for adding and removing nodes and edges, as well as accessing and modifying their attributes.
4. Extensive Algorithms: Implements a vast collection of standard graph algorithms, including:
- Pathfinding: Shortest path (Dijkstra, A-), all-pairs shortest path.
- Connectivity: Connected components, strongly connected components, bridges, articulation points.
- Centrality: Degree centrality, betweenness centrality, closeness centrality, eigenvector centrality, PageRank.
- Community Detection: Clustering coefficient, modularity.
- Flows: Max-flow min-cut.
5. Drawing: Although NetworkX itself doesn't provide sophisticated visualization tools, it integrates well with Matplotlib for basic graph drawing and can export graph data to formats suitable for more advanced visualization libraries like Graphviz.
6. Data Formats: Supports reading and writing graphs in various formats such as GML, GraphML, Pajek, and edge lists.
NetworkX is widely used in diverse fields such as social network analysis, bioinformatics, neuroscience, urban planning, machine learning, and many others where understanding relationships and structures is crucial.
Example Code
import networkx as nx
import matplotlib.pyplot as plt
1. Create an empty undirected graph
G = nx.Graph()
2. Add nodes
G.add_node("Alice")
G.add_node("Bob", age=30)
G.add_nodes_from(["Charlie", "David", "Eve"])
3. Add edges
G.add_edge("Alice", "Bob", weight=1)
G.add_edge("Bob", "Charlie", friendship_type="best")
G.add_edges_from([("Charlie", "David"), ("David", "Eve"), ("Eve", "Alice")])
You can also add edges with attributes directly
G.add_edge("Bob", "Eve", interaction="work")
4. Accessing graph information
print("Nodes:", G.nodes(data=True)) data=True to see attributes
print("Edges:", G.edges(data=True)) data=True to see attributes
print("Number of nodes:", G.number_of_nodes())
print("Number of edges:", G.number_of_edges())
5. Graph analysis: Calculate degree centrality
degree_centrality = nx.degree_centrality(G)
print("Degree Centrality:", degree_centrality)
6. Graph analysis: Find shortest path
try:
shortest_path = nx.shortest_path(G, source="Alice", target="David")
print(f"Shortest path from Alice to David: {shortest_path}")
except nx.NetworkXNoPath:
print("No path found between Alice and David")
7. Drawing the graph
plt.figure(figsize=(8, 6))
pos = nx.spring_layout(G) Layout algorithm for node positioning
Draw nodes
nx.draw_networkx_nodes(G, pos, node_color='lightblue', node_size=2000)
Draw edges
nx.draw_networkx_edges(G, pos, width=2, edge_color='gray', alpha=0.7)
Draw node labels
nx.draw_networkx_labels(G, pos, font_size=12, font_weight='bold')
Draw edge labels (e.g., weight attribute)
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color='red')
plt.title("Simple NetworkX Graph Example")
plt.axis('off') Hide axes
plt.show()
Example with a directed graph (DiGraph)
DG = nx.DiGraph()
DG.add_edges_from([('A', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'D')])
print("\nDirected Graph Nodes:", DG.nodes())
print("Directed Graph Edges:", DG.edges())
plt.figure(figsize=(6, 5))
pos_dg = nx.spring_layout(DG) Layout for directed graph
nx.draw_networkx(DG, pos_dg, with_labels=True, arrowsize=20, node_color='lightcoral', font_weight='bold')
plt.title("Directed Graph Example")
plt.axis('off')
plt.show()








networkx