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

如何在Matplotlib极坐标图外部添加飞机航向指示箭头?

在Matplotlib极坐标图外部添加航向箭头的实现方法

要在Matplotlib极坐标图外部添加指向中心的航向箭头,核心是利用Matplotlib的坐标转换系统,在绘图区域外确定箭头起点,再连接到极坐标图边缘对应航向的位置。以下是具体实现步骤和代码:

完整代码示例

import matplotlib.pyplot as plt
import numpy as np

# 创建极坐标图
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(6,6))

# 示例极坐标数据(可替换为你的实际数据)
theta = np.linspace(0, 2*np.pi, 100)
r = np.sin(3*theta)
ax.plot(theta, r)

# 设置目标航向(单位:度,可替换为实际航向值)
heading_deg = 225
heading_rad = np.deg2rad(heading_deg)

# 获取极坐标图的最大半径(确保箭头连接到绘图边缘)
max_radius = ax.get_ylim()[1]
# 箭头终点:极坐标边缘对应航向的位置(数据坐标)
arrow_end = (heading_rad, max_radius)

# 坐标转换:将数据坐标转为figure归一化坐标(便于在外部定位)
end_point_fig = ax.transData.transform(arrow_end)
end_point_norm = fig.transFigure.inverted().transform(end_point_fig)

# 计算箭头起点:沿航向方向向外偏移(offset控制偏移距离)
offset = 0.15
# 极坐标角度转笛卡尔方向向量(调整方向确保箭头向外延伸)
dir_x = np.cos(heading_rad + np.pi/2)
dir_y = np.sin(heading_rad + np.pi/2)
start_point_norm = (
    end_point_norm[0] + dir_x * offset,
    end_point_norm[1] + dir_y * offset
)

# 转换回数据坐标用于绘制箭头
start_point_data = ax.transData.inverted().transform(fig.transFigure.transform(start_point_norm))
end_point_data = ax.transData.inverted().transform(end_point_fig)

# 绘制箭头
ax.annotate(
    '',
    xy=end_point_data,
    xytext=start_point_data,
    arrowprops=dict(facecolor='#ff4444', shrink=0.05, width=2, headwidth=8),
    zorder=10  # 让箭头显示在所有图层上方
)

# 可选:添加航向角度标签
ax.text(
    start_point_norm[0] + dir_x*0.05,
    start_point_norm[1] + dir_y*0.05,
    f'{heading_deg}°',
    transform=fig.transFigure,
    ha='center', va='center',
    fontweight='bold', fontsize=12
)

plt.show()

关键细节说明

  1. 坐标转换逻辑

    • 先将极坐标边缘的终点从数据坐标(极坐标的(θ, r))转换为figure归一化坐标(0-1对应整个画布的范围),方便计算外部起点位置。
    • 再将外部起点的归一化坐标转回数据坐标,确保箭头能在极坐标轴上正确绘制。
  2. 方向控制
    极坐标的0度对应笛卡尔坐标系的x轴正方向(向右),通过heading_rad + np.pi/2调整方向向量,保证箭头沿着航向的反方向向外延伸(即从外部指向极坐标中心)。

  3. 样式调整

    • 修改offset值可以控制箭头向外延伸的距离,数值越大箭头越靠外。
    • 通过arrowprops可以自定义箭头的颜色、粗细、箭头头部大小等样式,匹配你的可视化需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:57:13