Cartopy代码替换为Robinson投影时报错的原因分析及解决方案咨询
Robinson投影报错原因与解决方案
我来帮你拆解这个问题,搞清楚为什么Robinson投影会报错,而Orthographic投影却能正常运行:
报错核心原因
Robinson投影属于伪圆柱投影,它对输入数据的网格结构要求比Orthographic(正射透视投影)严格得多:
- 当你使用
shading='nearest'(平着色)时,matplotlib/cartopy要求你的数据数组dia_depth_smooth必须是和x(geolon_t)、y(geolat_t)对应的二维网格数据。从报错信息看,你的x轴有361个点、y轴有201个点,那么数据应该是(200, 360)或(201, 361)的二维形状。 - 但你的数据实际形状是
(263,)——这是一个一维数组,完全不符合Robinson投影对网格数据的要求。 - 而Orthographic投影是透视类投影,它对非规则或一维点数据的兼容性更强,所以能绕过这个校验正常运行。
针对性解决方案
根据你的数据类型,选择对应的修复方式:
情况1:数据原本是二维网格,被意外扁平化了
如果dia_depth_smooth应该是和经纬度网格匹配的二维数组,先检查并恢复它的形状:
# 先确认当前数据和经纬度的形状 print("数据形状:", dia_depth_smooth.shape) print("经度形状:", geolon_t.shape) print("纬度形状:", geolat_t.shape) # 如果数据是被扁平化的,根据经纬度维度恢复形状(示例) # 假设经纬度是(361,)和(201,),数据应该是(201, 361)或(200, 360) dia_depth_smooth = dia_depth_smooth.reshape(201, 361)
情况2:数据是零散的点数据(非网格)
如果dia_depth_smooth是263个离散点的数值,需要先把这些点插值到规则的经纬度网格上,再进行投影绘图:
import numpy as np from scipy.interpolate import griddata # 假设你有原始离散点的经纬度和对应深度:lon_points, lat_points, depth_points # 生成和原代码匹配的规则经纬度网格 lon_grid, lat_grid = np.meshgrid(geolon_t, geolat_t) # 插值到网格(可选method='linear'/'cubic',根据需求选择) dia_depth_smooth = griddata((lon_points, lat_points), depth_points, (lon_grid, lat_grid), method='nearest')
情况3:直接改用散点图适配点数据
如果不想做插值,也可以放弃网格绘图,改用散点图方式展示,这样无需调整数据形状:
# 替换原有的plot调用为scatter scatter = ax.scatter( x='geolon_t', y='geolat_t', c=dia_depth_smooth, cmap=cm.cm.deep, vmin=0, vmax=2500, transform=ccrs.PlateCarree(), ) # 手动添加颜色条(和原代码逻辑对齐) cb = plt.colorbar(scatter, shrink=0.8, aspect=40, pad=0.04, orientation="horizontal", label="Diapause Depth (metres)") cb.ax.yaxis.set_minor_locator(AutoMinorLocator())
额外注意事项
- 确保
geolon_t和geolat_t是二维网格:如果它们目前是一维数组,最好先用np.meshgrid转成二维,避免后续绘图出现兼容问题:geolon_t, geolat_t = np.meshgrid(geolon_t, geolat_t) - 匹配
shading参数和数据类型:只有二维网格数据适合用'nearest'或'flat'这类着色模式,点数据不要使用这些参数。
内容的提问来源于stack exchange,提问作者Si Chen
相关产品推荐
相关产品推荐

