NetworkX Python Tutorial: Graph Basics
To utilize the networkx library in Python, you first need to install it. You can install it using the following command:
pip install networkx
Once the installation is complete, you can import the networkx library in the Python script and start using it. Below is a simple example that demonstrates how to create a basic graph and perform some basic operations:
import networkx as nx
# 创建一个空图
G = nx.Graph()
# 添加节点
G.add_node(1)
G.add_nodes_from([2, 3, 4])
# 添加边
G.add_edge(1, 2)
G.add_edges_from([(2, 3), (3, 4)])
# 查看节点和边的数量
print("Number of nodes:", G.number_of_nodes())
print("Number of edges:", G.number_of_edges())
# 遍历节点和边
print("Nodes:", G.nodes())
print("Edges:", G.edges())
# 计算图的直径
print("Diameter:", nx.diameter(G))
# 可视化图
nx.draw(G, with_labels=True)
This is just a small portion of the functionalities offered by the networkx library. It also provides many other capabilities such as various graph algorithms, graph visualization, and graph analysis. Check the official networkx documentation for more information.