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

Networkx中表示债务关系的图箭头方向错误该如何修正?

问题原因与修正方案

你的代码里用了nx.Graph(),这是无向图,无向图的边没有固定方向,所以即使设置了箭头,绘图时的箭头方向是随机的,导致最后两个边的指向不符合预期。

要解决这个问题,只需要把无向图换成有向图nx.DiGraph(),有向图会严格保留你添加边时的方向(source→sink)。

修正后的完整代码

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

df = pd.DataFrame({'source': [1, 2, 3, 4, 5], 'sink': [3, 4, 5, 1, 2]})

# 替换为有向图
G = nx.DiGraph()
for row in df.iterrows():
    G.add_edge(row[1]['source'], row[1]['sink'])

pos = nx.spring_layout(G)
nodes = nx.draw_networkx_nodes(G, pos, node_color="orange")
nx.draw_networkx_labels(G, pos)
edges = nx.draw_networkx_edges(
    G,
    pos,
    arrows=True,
    arrowstyle="->",
    arrowsize=10,
    width=2,
)

# 显示图形
plt.show()

说明

  • 换成nx.DiGraph()后,每一条add_edge(source, sink)都会创建一条从source指向sink的有向边,完全符合你期望的箭头方向:1→3、2→4、3→5、4→1、5→2。
  • 其他绘图参数不需要调整,箭头会自动对应有向边的方向。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:52:12