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

NetworkX中提取带高权重粗边的子图问题求助

解决方案

你的问题根源是整个原图本身是强连通的,所以strongly_connected_components会返回所有节点。要提取高权重边的子图,得先过滤边再处理,具体步骤如下:

1. 筛选高权重边

从计数结果ct里挑出出现次数(即边权重)大于2的边:

# 过滤权重>2的边,阈值可根据需求调整
high_weight_edges = [edge for edge, cnt in ct.items() if cnt > 2]

2. 构建高权重边子图

两种方式生成子图:

# 方式一:从已有图中提取边子图
high_weight_subgraph = pattern_g.edge_subgraph(high_weight_edges)

# 方式二:直接新建图并添加带权重的高权重边
high_weight_subgraph = nx.DiGraph()
for edge, cnt in ct.items():
    if cnt > 2:
        high_weight_subgraph.add_edge(*edge, weight=cnt)

3. 绘制高权重子图

计算边宽并绘制:

widths = [ct[edge] for edge in high_weight_subgraph.edges]
nx.draw(high_weight_subgraph, node_color='orange', with_labels=True, width=widths)
plt.show()

可选:提取子图中的强连通分量

如果需要在高权重子图里找强连通分量,直接对子图调用方法即可:

# 获取所有强连通分量
scc_list = list(nx.strongly_connected_components(high_weight_subgraph))
# 取最大的强连通分量绘制
largest_scc = max(scc_list, key=len)
scc_subgraph = high_weight_subgraph.subgraph(largest_scc)

# 绘制强连通分量子图
scc_widths = [ct[edge] for edge in scc_subgraph.edges]
nx.draw(scc_subgraph, node_color='orange', with_labels=True, width=scc_widths)
plt.show()

内容的提问来源于stack exchange,提问作者black street boy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:31:06