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

如何将Matplotlib极坐标图叠加至Folium地图指定位置?

实现陀螺仪校准罗盘玫瑰图叠加到Folium地图的方案

1. 生成透明背景的Matplotlib极坐标图

要让Matplotlib生成的极坐标图背景透明,需在绘图和保存阶段做两处关键设置:

  • 创建画布时指定facecolor='none',消除默认白色背景
  • 保存图片时启用transparent=True,确保背景像素完全透明

修改后的示例代码如下:

import matplotlib.pyplot as plt
import numpy as np

# 模拟陀螺仪校准数据:修正后航向、太阳轨迹点
corrected_heading = np.array([0, 45, 90, 135, 180, 225, 270, 315])
sun_trajectory = np.random.uniform(0, 360, 20)

# 创建极坐标画布,设置透明背景
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(6, 6), facecolor='none')

# 配置罗盘玫瑰图基础参数
ax.set_theta_zero_location('N')  # 正北为0度基准
ax.set_theta_direction(-1)  # 航向按顺时针方向递增
ax.set_xticks(np.deg2rad([0, 90, 180, 270]))
ax.set_xticklabels(['N', 'E', 'S', 'W'])

# 绘制修正后陀螺航向
ax.plot(np.deg2rad(corrected_heading), np.ones_like(corrected_heading)*0.8, 'ro-', label='修正后航向')
# 绘制太阳轨迹点
ax.plot(np.deg2rad(sun_trajectory), np.random.uniform(0.5, 1, 20), 'b.', label='太阳轨迹')

ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
ax.grid(True)

# 保存为透明背景PNG(SVG格式只需将后缀改为.svg)
plt.savefig('gyro_compass_rose.png', transparent=True, bbox_inches='tight', dpi=150)
plt.close()

关键细节:

  • facecolor='none':确保画布本身无底色
  • transparent=True:导出时移除所有背景像素,仅保留绘图内容
  • bbox_inches='tight':裁剪图像周围空白,避免叠加到地图时出现多余留白

2. 将透明图像叠加到Folium地图指定位置

使用Folium的ImageOverlay类,可将生成的PNG/SVG精准叠加到指定经纬度区域。需根据地图缩放级别,调整图像的边界范围(bounds参数)以匹配实际位置。

示例代码:

import folium

# 船舶停泊港口的经纬度
port_lat = 31.2304
port_lon = 121.4737

# 初始化地图,中心对准停泊位置
m = folium.Map(location=[port_lat, port_lon], zoom_start=15)

# 设置图像叠加边界:以停泊点为中心,向四周扩展0.001度(可根据缩放级别调整)
bounds = [
    [port_lat - 0.001, port_lon - 0.001],
    [port_lat + 0.001, port_lon + 0.001]
]

# 添加透明图像到地图
folium.raster_layers.ImageOverlay(
    image='gyro_compass_rose.png',
    bounds=bounds,
    opacity=0.8,  # 调整透明度,平衡图像可见性与地图可读性
    name='陀螺仪校准罗盘玫瑰图'
).add_to(m)

# 添加图层控制器,方便开关图像显示
folium.LayerControl().add_to(m)

# 保存地图为HTML文件
m.save('gyro_calibration_map.html')

关键细节:

  • bounds参数需随地图缩放级别调整:缩放级越高,边界范围应越小,保证图像与实际位置匹配
  • 若使用SVG格式,直接将image参数改为SVG文件路径即可,Folium原生支持SVG格式叠加

内容的提问来源于stack exchange,提问作者mR.bLuEsKy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:36:11