You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于NetworkX识别无向网络核心节点及可视化实现问询

实现代码(以扎卡里空手道俱乐部为示例)
import networkx as nx
import matplotlib.pyplot as plt

# 加载示例网络
G = nx.karate_club_graph()

# 计算两类中心度(与你现有逻辑一致)
degCent = nx.degree_centrality(G)
betCent = nx.betweenness_centrality(G, normalized=True, endpoints=True)

# 筛选两类中心度Top10节点
top_deg_nodes = [i[0] for i in sorted(degCent.items(), key=lambda x: x[1], reverse=True)[:10]]
top_bet_nodes = [i[0] for i in sorted(betCent.items(), key=lambda x: x[1], reverse=True)[:10]]
# 合并去重得到所有待关注节点
focus_nodes = list(set(top_deg_nodes + top_bet_nodes))

# 预计算全网络布局,固定seed保证节点位置和全网络真实位置一致
pos = nx.spring_layout(G, seed=42)

# 配置样式:关注节点绿色+显示标签,其余节点红色+隐藏标签
node_color = []
node_label = {}
node_size = []
for node in G.nodes():
    if node in focus_nodes:
        node_color.append("#2ecc71")
        node_label[node] = node
        node_size.append(300)
    else:
        node_color.append("#e74c3c")
        node_label[node] = ""
        node_size.append(10)

# 绘制全网络定位图
plt.figure(figsize=(12, 8))
nx.draw_networkx_nodes(G, pos, node_color=node_color, node_size=node_size)
nx.draw_networkx_edges(G, pos, alpha=0.15)
nx.draw_networkx_labels(G, pos, labels=node_label, font_weight="bold")
plt.axis("off")
plt.show()

# 如果仅需要查看关注节点之间的连接关系,绘制子图即可
sub_G = G.subgraph(focus_nodes)
plt.figure(figsize=(8, 6))
nx.draw(sub_G, pos={n: pos[n] for n in sub_G.nodes()}, node_color="#2ecc71", with_labels=True, node_size=500, font_weight="bold")
plt.axis("off")
plt.show()
针对5000节点规模的优化建议
  • 中心度计算优化:nx.betweenness_centrality默认全节点遍历计算复杂度为O(nm),5000节点规模运行速度较慢,可添加k参数启用抽样计算,例如nx.betweenness_centrality(G, k=1000, normalized=True, endpoints=True),抽取1000个节点做近似计算,误差可控的前提下速度提升数倍。
  • 布局计算优化:无需重复计算子图布局,预计算一次全网络的布局坐标后直接复用,既可以保证关注节点的位置和全网络中的真实位置一致,也能减少布局计算开销。
  • 展示效果优化:可以新增颜色区分仅度中心度Top10、仅中介中心度Top10、同时进入两个榜单的三类节点,比单一绿色辨识度更高;如果全网络绘制过于杂乱,可仅保留关注节点及它们之间的最短路径节点做展示,既能体现位置关系也不会过于拥挤。
  • 性能优化:如果不需要在全网络下定位,直接提取关注节点生成子图后再做布局和绘制,内存和时间开销都会低很多。

内容的提问来源于stack exchange,提问作者Math

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 18:15:03