升级Matplotlib后出现‘QuadContourSet对象无setter属性’错误求助
解决'QuadContourSet' object has no setter错误
问题根源
你遇到的错误是因为Basemap已停止维护,升级后的新版本matplotlib(3.4+)对QuadContourSet类的API做了修改,移除了某些属性的setter方法,而Basemap的contour方法返回的对象在调用plt.clabel()时触发了这个不兼容操作。
解决方案
方案1:降级matplotlib到兼容版本
直接将matplotlib降级到Basemap支持的最后稳定版本,比如3.3.x系列,无需修改代码:
pip install matplotlib==3.3.4
方案2:替换Basemap为Cartopy(推荐长期方案)
Basemap已被官方弃用,Cartopy是替代库,支持最新版matplotlib,功能更完善。以下是核心代码迁移示例:
# 替换Basemap导入为Cartopy相关模块 import cartopy.crs as ccrs import cartopy.feature as cfeature # 创建绘图轴时指定投影 ax = fig.add_subplot(111, projection=ccrs.Mercator()) # 设置地图显示范围 ax.set_extent([0, 80, 10, 45], crs=ccrs.PlateCarree()) # 绘制地图要素 ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.STATES) ax.add_feature(cfeature.COUNTRIES) ax.add_feature(cfeature.LAND, facecolor='Linen') ax.add_feature(cfeature.OCEAN, facecolor='#CCFFFF') # 配置经纬网 gl = ax.gridlines(draw_labels=True, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False gl.xlocator = ticker.FixedLocator(np.arange(40,70,5)) gl.ylocator = ticker.FixedLocator(np.arange(15,45,5)) gl.xlabel_style = {'fontsize':10, 'fontweight':'bold', 'fontstyle':'oblique'} gl.ylabel_style = {'fontsize':10, 'fontweight':'bold', 'fontstyle':'oblique'} # 绘制填色图与等值线(需指定坐标转换) cs1 = ax.contourf(lon, lat, sh[0,:,:], clevs1, cmap='RdBu', transform=ccrs.PlateCarree()) cs2 = ax.contour(lon, lat, omega[0,:,:], clevs2, colors='blue', linewidths=1., transform=ccrs.PlateCarree()) ax.clabel(cs2, fontsize=9, inline=1)
方案3:临时修改代码适配新版matplotlib
若不想换库或降级,尝试替换plt.clabel()的调用方式,直接使用轴对象的clabel方法:
# 替换原代码中的plt.clabel(cs2, fontsize=9, inline=1) ax.clabel(cs2, fontsize=9, inline=1)
注:该方法仅为临时适配,无法解决Basemap与新版matplotlib的所有兼容问题。
内容的提问来源于stack exchange,提问作者Sedighe
相关产品推荐
相关产品推荐

