力导向网络图:NetworkX 1 行出图
Force-directed Graph with NetworkX
共现矩阵是数字,网络图是故事。一张力导向图能直接告诉老板:评论里物流和客服是一个圈子,屏幕和续航是另一个圈子 — 一图胜千言。
1. 从矩阵构图
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
for (w1, w2), count in strong_pairs.items():
G.add_edge(w1, w2, weight=count)
for node in G.nodes():
G.nodes[node]['size'] = sum(d['weight'] for _, _, d in G.edges(node, data=True))
print(f'节点: {G.number_of_nodes()}, 边: {G.number_of_edges()}')
2. 力导向布局 + 画图
plt.figure(figsize=(14, 10))
pos = nx.spring_layout(G, k=0.5, iterations=50)
sizes = [G.nodes[n]['size'] / 50 for n in G.nodes()]
widths = [G[u][v]['weight'] / 100 for u, v in G.edges()]
nx.draw_networkx_nodes(G, pos, node_size=sizes, alpha=0.6,
node_color=range(len(G)), cmap=plt.cm.tab20)
nx.draw_networkx_edges(G, pos, width=widths, alpha=0.3, edge_color='gray')
nx.draw_networkx_labels(G, pos, font_size=9, font_family='PingFang SC')
plt.title('评论共现网络图(节点大小=词频,边粗细=共现强度)', fontsize=14)
plt.axis('off')
plt.tight_layout()
plt.savefig('co_network.png', dpi=150, bbox_inches='tight')
力导向布局原理:节点之间有引力(相似词拉近)和斥力(所有词相互排斥),系统迭代求解最优位置。NetworkX 的
spring_layout 是一行调用,但参数 k 和 iterations 需要调。
3. 社区检测:自动找主题圈
from networkx.algorithms.community import greedy_modularity_communities
communities = list(greedy_modularity_communities(G))
print(f'检测到 {len(communities)} 个社区')
for i, comm in enumerate(communities[:5]):
print(f'社区 {i}: {", ".join(list(comm)[:8])}')
社区检测 = 自动给网络图分区上色 — 同一社区的词是同一主题。这是从关系数据提炼主题洞察的关键一步。