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

如何在NetworkX中调整边13的位置使其绕到正方形外侧?

解决方法:让NetworkX中边1-3绕到正方形外侧

NetworkX本身不会存储边的绘制路径,默认布局会让边走最短路径。要实现边绕到正方形外侧,需要手动指定这条边的绘制路径,具体操作如下:

  • 先固定四个节点的位置,对应你标注的顺时针1-4顺序
  • 用NetworkX绘制节点和其他正常边
  • 借助Matplotlib单独绘制这条边的绕行路径

代码示例

import networkx as nx
import matplotlib.pyplot as plt

# 创建图结构
G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1,2), (2,3), (3,4), (4,1), (1,3)])

# 定义节点位置:左上角顺时针1到4
pos = {1: (0, 1), 2: (1, 1), 3: (1, 0), 4: (0, 0)}

# 绘制节点和除1-3外的所有边
nx.draw(G, pos, edgelist=[(1,2), (2,3), (3,4), (4,1)], 
        with_labels=True, node_color='lightblue', font_weight='bold')

# 自定义边1-3的外侧路径(这里绕正方形上方)
# 路径坐标:从节点1出发,向上延伸,再右移,最后到节点3
outer_edge = [(0, 1), (0, 1.5), (1, 1.5), (1, 0)]
plt.plot([p[0] for p in outer_edge], [p[1] for p in outer_edge], 'k-', linewidth=2)

plt.show()

调整绕行方向

如果想让边绕到其他外侧(比如下方、左侧),只需要修改outer_edge的坐标即可:

  • 绕下方:outer_edge = [(0, 1), (0, -0.5), (1, -0.5), (1, 0)]
  • 绕左侧:outer_edge = [(0, 1), (-0.5, 1), (-0.5, 0), (1, 0)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:32:43