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

在NetworkX有向图中创建多条边并实现正确可视化的问题咨询

多重有向图绘制解决方案

现有代码问题

  • 使用nx.DiGraph()无法支持同节点对的多条边,会自动合并重复的源-目的地边,丢失数据
  • 边属性读取键名不匹配:生成图时传入的边属性是number of passengers,但代码中尝试读取不存在的Edge_label属性,导致边标签为空
  • 两次调用nx.draw()且第二次未传入位置参数pos,会导致节点位置错乱
  • 未处理多重边的显示偏移,就算生成了多条边也会完全重叠无法区分

修正后可运行代码

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# 示例数据集加载,你也可以替换为自己的读表代码
data = {
    'date': ['2019-01-01','2019-01-02','2019-01-03','2019-01-04','2019-01-05','2019-01-06'],
    'source': ['NY','NY','NY','BERLIN','NY','BERLIN'],
    'destination': ['BERLIN','PARIS','BERLIN','PARIS','PARIS','NY'],
    'number of passengers': [10,50,40,20,15,17]
}
df = pd.DataFrame(data)

# 1. 使用MultiDiGraph支持多重有向边
G = nx.from_pandas_edgelist(df, 'source', 'destination', edge_attr='number of passengers', create_using=nx.MultiDiGraph())

# 2. 固定节点位置,这里可以换用random_layout、circular_layout等其他布局
pos = nx.spring_layout(G, seed=42)  # seed固定布局避免每次运行位置变化

# 3. 绘制节点、节点标签和边
nx.draw(G, pos=pos, with_labels=True, node_size=1500, node_color='lightblue', font_size=10, font_weight='bold', arrowstyle='->', arrowsize=20)

# 4. 处理多重边标签偏移,避免重叠
edge_labels = {}
for (u, v, key), attr in G.edges(data=True, keys=True):
    # 同节点对的不同边设置阶梯式偏移量
    offset = 0.1 * key
    edge_labels[(u, v, key)] = f"乘客数: {attr['number of passengers']}"

# 5. 绘制带偏移的边标签
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, label_pos=0.5, font_size=8)

plt.show()

效果说明

  • 同一源、目的地之间的多条边会自动调整位置避免完全重叠
  • 边标签会正确显示对应线路的乘客数量
  • 固定随机种子保证每次运行生成的布局一致,方便调试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:24:02