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

如何在Matplotlib中创建可旋转的单头箭头标记?

解决matplotlib 2.2.5中旋转单头箭头标记的问题

由于matplotlib 2.2.5没有内置<--这类箭头标记,你需要先自定义箭头的路径,再通过MarkerStyle给路径添加旋转变换,就能实现和标准标记一致的旋转效果。以下是完整实现方案:

方法一:自定义路径实现可旋转箭头标记

这种方式和你原有的标准标记旋转逻辑完全兼容,适合批量绘制带朝向的点:

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.path import Path

# 定义<--形状的箭头路径顶点
arrow_vertices = [
    (0.0, 0.0),    # 箭头尖端
    (-0.5, 0.2),   # 箭头左上侧
    (-0.3, 0.0),   # 箭杆上连接点
    (-1.0, 0.0),   # 箭杆左端
    (-0.3, -0.0),  # 箭杆下连接点
    (-0.5, -0.2),  # 箭头左下侧
    (0.0, 0.0),    # 回到尖端闭合路径
]
# 路径绘制指令:移动、连线、闭合
arrow_codes = [
    Path.MOVETO,
    Path.LINETO,
    Path.LINETO,
    Path.LINETO,
    Path.LINETO,
    Path.LINETO,
    Path.CLOSEPOLY,
]
arrow_path = Path(arrow_vertices, arrow_codes)

# 批量绘制不同角度的旋转箭头
for i, angle in enumerate([0, 30, 60, 90]):
    rotated_marker = mpl.markers.MarkerStyle(marker=arrow_path)
    rotated_marker._transform = rotated_marker.get_transform().rotate_deg(angle)
    plt.scatter(i, 0, marker=rotated_marker, s=200)  # s参数控制标记大小

plt.xlim(-0.5, 3.5)
plt.ylim(-0.5, 0.5)
plt.show()

关键细节

  • 你可以修改arrow_vertices里的坐标值,调整箭头的长短、粗细和形状。
  • 旋转变换的逻辑和你原代码完全一致,直接复用即可。

方法二:用annotate快速实现旋转箭头

如果不需要严格的散点标记样式,也可以用annotate直接绘制旋转箭头,代码更简洁:

import matplotlib.pyplot as plt

for i, angle in enumerate([0, 30, 60, 90]):
    plt.annotate('', xy=(i, 0), xytext=(i-0.5, 0),
                 arrowprops=dict(arrowstyle='<-', rotation=angle))

plt.xlim(-0.5, 3.5)
plt.ylim(-0.5, 0.5)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:01:18