[ PROMPT_NODE_26860 ]
Networkx 可视化
[ SKILL_DOCUMENTATION ]
# NetworkX 图可视化
## 使用 Matplotlib 进行基础绘图
### 简单可视化
python
import networkx as nx
import matplotlib.pyplot as plt
# 创建并绘制图
G = nx.karate_club_graph()
nx.draw(G)
plt.show()
# 保存到文件
nx.draw(G)
plt.savefig('graph.png', dpi=300, bbox_inches='tight')
plt.close()
### 带标签绘图
python
# 绘制带节点标签的图
nx.draw(G, with_labels=True)
plt.show()
# 自定义标签
labels = {i: f"Node {i}" for i in G.nodes()}
nx.draw(G, labels=labels, with_labels=True)
plt.show()
## 布局算法
### 弹簧布局 (力导向)
python
# Fruchterman-Reingold 力导向算法
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
# 带参数
pos = nx.spring_layout(G, k=0.5, iterations=50, seed=42)
### 圆形布局
python
# 将节点排列成圆形
pos = nx.circular_layout(G)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
### 随机布局
python
# 随机定位
pos = nx.random_layout(G, seed=42)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
### 外壳布局
python
# 同心圆
pos = nx.shell_layout(G)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
# 自定义外壳
shells = [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9]]
pos = nx.shell_layout(G, nlist=shells)
### 谱布局
python
# 使用图拉普拉斯矩阵的特征向量
pos = nx.spectral_layout(G)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
### Kamada-Kawai 布局
python
# 基于能量的布局
pos = nx.kamada_kawai_layout(G)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
### 平面布局
python
# 仅适用于平面图
if nx.is_planar(G):
pos = nx.planar_layout(G)
nx.draw(G, pos=pos, with_labels=True)
plt.show()
### 树状布局
python
# 适用于树图
if nx.is_tree(G):
pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
nx.draw(G, pos=pos, with_labels=True)
plt.show()
## 自定义节点外观
### 节点颜色
python
# 单一颜色
nx.draw(G, node_color='red')
# 每个节点不同颜色
node_colors = ['red' if G.degree(n) > 5 else 'blue' for n in G.nodes()]
nx.draw(G, node_color=node_colors)
# 按属性着色
colors = [G.nodes[n].get('value', 0) for n in G.nodes()]
nx.draw(G, node_color=colors, cmap=plt.cm.viridis)
plt.colorbar()
plt.show()
### 节点大小
python
# 按度数调整大小
node_sizes = [100 * G.degree(n) for n in G.nodes()]
nx.draw(G, node_size=node_sizes)