import networkx as nx
import matplotlib.pyplot as plt
# 创建一个空的无向图
G = nx.Graph()
# 添加节点
G.add_nodes_from([1, 2, 3, 4, 5])
# 指定每个节点的位置
pos = {1: (0, 0),
2: (1, 1),
3: (2, 0),
4: (1, -1),
5: (-1, -1)}
# 添加边
G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5)])
# 指定节点的颜色
node_colors = ['red' if node == 1 else 'blue' if node == 2 else 'lightblue' for node in G.nodes()]
# 绘制图形
nx.draw(G, pos, with_labels=True, node_size=500, node_color=node_colors, font_size=12, font_color='black')
# 显示图形
plt.show()
动画
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 创建一个空的无向图
G = nx.Graph()
# 添加节点和边
G.add_edges_from([(1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (4, 5)])
# 创建初始图形
fig, ax = plt.subplots()
# 初始化绘制函数
def init():
nx.draw(G, with_labels=True, node_size=500, node_color='lightblue', font_size=12, font_color='black')
# 更新绘制函数
def update(frame):
ax.clear()
# 更新图形状态或布局,这里只作为示例没有进行更新操作
# 这里可以添加你自己的更新逻辑
nx.draw(G, with_labels=True, node_size=500, node_color='lightblue', font_size=12, font_color='black')
# 创建动画
ani = animation.FuncAnimation(fig, update, frames=10, init_func=init, interval=33) # 33毫秒为每帧的间隔时间,约等于30帧每秒
# 显示动画
plt.show()