如何将matplotlib pyplot的clabel文本方向设置为正立状态?
Matplotlib 3.4+版本等高线标注(clabel)正立显示解决方案
报错原因说明
你遇到的NoneType错误是版本适配问题导致:Matplotlib 3.4及以上版本中,开启use_clabeltext=True参数后,plt.clabel()方法不再返回标注文本对象列表,所以直接遍历返回值会触发类型错误。
两种可直接使用的实现方案
- 方案1:直接在clabel参数中指定旋转角度,无需额外遍历
移除use_clabeltext和rightside_up参数,直接传入rotation=0即可直接生成正立标注,代码示例:
im = plt.pcolormesh(lon, lat, values, cmap=colormap, vmax=40, vmin=-40, transform=ccrs.PlateCarree()) lvls = np.arange(-40, 40, 5) ctr = plt.contour(lon, lat, values, levels=lvls, colors='#242424', linewidths=0.1, transform=ccrs.PlateCarree()) # 直接指定rotation=0即可生成正立标注 cls = plt.clabel(ctr, inline=True, fontsize=5, fmt="%d", colors='#242424', rotation=0)
- 方案2:保留原有参数,从contour对象直接获取标注文本
如果需要保留use_clabeltext=True和rightside_up=True参数,可直接从contour实例的clabels属性中获取所有标注文本对象进行设置,无需接收clabel的返回值,代码示例:
im = plt.pcolormesh(lon, lat, values, cmap=colormap, vmax=40, vmin=-40, transform=ccrs.PlateCarree()) lvls = np.arange(-40, 40, 5) ctr = plt.contour(lon, lat, values, levels=lvls, colors='#242424', linewidths=0.1, transform=ccrs.PlateCarree()) plt.clabel(ctr, inline=True, fontsize=5, fmt="%d", colors='#242424', rightside_up=True, use_clabeltext=True) # 从contour对象的clabels属性存储了所有标注文本对象 for label in ctr.clabels: label.set_rotation(0)
以上两种方案均兼容Matplotlib 3.4及以上版本,均可实现clabel文本正立显示的需求。
内容的提问来源于stack exchange,提问作者Woodz
相关产品推荐
相关产品推荐

