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

使用Cartopy在地图绘制饼图时出现位置偏移该如何解决?

问题原因

你传入bbox_to_anchor的(lon, lat)是原始经纬度值(对应ccrs.PlateCarree地理坐标系),但ax.transData对应的是Miller投影后的平面坐标系,二者坐标系不匹配,因此会出现固定的位置偏移。

解决方法

先把需要放置饼图的经纬度坐标,转换为你当前使用的Miller投影的平面坐标,再传入bbox_to_anchor即可。
你只需要修改创建子图的相关代码:

# 原始经纬度转Miller投影坐标
proj_x, proj_y = proj.transform_point(lon, lat, src_crs=ccrs.PlateCarree())
ax_sub = inset_axes(ax, width=0.4, height=0.4, loc=10, bbox_to_anchor=(proj_x, proj_y), bbox_transform=ax.transData)

另外建议调整代码顺序,把ax.set_extent语句放到创建子图之前,避免范围变动导致坐标计算偏差,完整修改后的代码如下:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cf
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

# 西班牙地理中心点经纬度
lon, lat = (-4, 40)

fig = plt.figure(figsize=(10,8))
proj = ccrs.Miller(central_longitude=0)
ax = fig.add_subplot(1,1,1, projection=proj)
ax.add_feature(cf.COASTLINE, lw=0.5, edgecolor='gray')
ax.add_feature(cf.BORDERS, lw=0.5, edgecolor='gray')
# 先设置地图范围
ax.set_extent ((-12, 44, 35, 88), ccrs.Miller())
# 坐标转换后再创建子图
proj_x, proj_y = proj.transform_point(lon, lat, ccrs.PlateCarree())
ax_sub = inset_axes(ax, width=0.4, height=0.4, loc=10, bbox_to_anchor=(proj_x, proj_y), bbox_transform=ax.transData)
ax_sub.pie([10, 25, 5, 30, 50, 10], wedgeprops={'edgecolor': 'gray','linewidth': 0.25})
plt.show()

内容的提问来源于stack exchange,提问作者Jiun-Yan Ding

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:30:01