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

matplotlib绘制箭头时箭头头部出现异常竖线问题求助

解决Matplotlib绘制箭头时出现异常竖线的问题

当在x轴数值极大(如3e10)、y轴数值极小(如1e-9量级)的坐标系中用ax.arrow()画箭头时,会出现一条莫名的超长竖线——只有y值远小于1时才会触发,调参数、改箭头方向都没用。

复现代码

import matplotlib.pyplot as plt

# 触发问题的参数
x_length = [30000000000.0]
y_length = [[7.7e-09, 1.613e-08]]
set_idx = 0
ax = plt.subplot(1,2,1)

# 出问题的箭头代码
arrow = ax.arrow(
    x_length[set_idx], 0, 
    0.04*x_length[set_idx], 0, 
    shape='full',
    head_width=max(y_length[set_idx])*0.04,
    head_length=0.04*x_length[set_idx],
    length_includes_head=True,
    color='black', 
    zorder=2
)

plt.show()

问题原因

ax.arrow()是Matplotlib里比较老的箭头实现,碰到坐标轴数值量级差得特别大的情况时,内部浮点计算容易精度丢失,导致渲染出错误的竖线。换成更现代的FancyArrowPatch就能解决这个兼容性问题。

修复方案:用FancyArrowPatch替代ax.arrow

把原箭头代码换成下面的实现,完全匹配原视觉效果,且不会出现异常竖线:

import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch

x_length = [30000000000.0]
y_length = [[7.7e-09, 1.613e-08]]
set_idx = 0
ax = plt.subplot(1,2,1)

# 计算箭头参数
x_start = x_length[set_idx]
# 匹配原length_includes_head=True的逻辑:箭头总长度包含头部,因此需要调整主体长度
total_arrow_length = 0.04 * x_length[set_idx]
head_length = 0.04 * x_length[set_idx]
x_end = x_start + (total_arrow_length - head_length)
y_pos = 0
head_width = max(y_length[set_idx]) * 0.04

# 绘制箭头
arrow = FancyArrowPatch(
    (x_start, y_pos), (x_end, y_pos),
    arrowstyle=f'-|>,head_width={head_width},head_length={head_length}',
    color='black',
    zorder=2
)
ax.add_patch(arrow)

plt.show()

补充说明

如果不需要length_includes_head的效果,直接把x_end设为x_start + 0.04*x_length[set_idx]即可,不用减去head_length。

内容的提问来源于stack exchange,提问作者Max Anacleto Vasconcelos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:40:44