为ContourPlot添加离散色条时遇__init__()缺失transform参数错误
解决plt.colorbar触发TypeError: init()缺少transform参数的问题
错误回溯
TypeError Traceback (most recent call last) Input In [552], in <cell line: 48>() 43 plt.contourf(to_np(lons), to_np(lats), to_np(dr_nested2), 10, 44 transform=crs.PlateCarree(), 45 cmap=get_cmap("jet"),extend='both',levels=lvl) 47 # Add a color bar ---> 48 plt.colorbar(ax=ax, shrink=.98) 50 # Add the gridlines 51 ax.gridlines(color="black", linestyle="dotted") File ~/anaconda3/lib/python3.9/site-packages/matplotlib/pyplot.py:2109, in colorbar(mappable, cax, ax, **kw) 2104 if mappable is None: 2105 raise RuntimeError('No mappable was found to use for colorbar ' 2106 'creation. First define a mappable such as ' 2107 'an image (with imshow) or a contour set (' 2108 'with contourf).') ---> 2109 ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kw) 2110 return ret File ~/anaconda3/lib/python3.9/site-packages/matplotlib/figure.py:1210, in FigureBase.colorbar(self, mappable, cax, ax, use_gridspec, **kw) 1206 NON_COLORBAR_KEYS = ['fraction', 'pad', 'shrink', 'aspect', 'anchor', 1207 'panchor'] 1208 cb_kw = {k: v for k, v in kw.items() if k not in NON_COLORBAR_KEYS} ---> 1210 cb = cbar.Colorbar(cax, mappable, **cb_kw) 1212 if not userax: 1213 self.sca(current_ax) File ~/anaconda3/lib/python3.9/site-packages/matplotlib/colorbar.py:483, in Colorbar.__init__(self, ax, mappable, cmap, norm, alpha, values, boundaries, orientation, ticklocation, extend, spacing, ticks, format, drawedges, filled, extendfrac, extendrect, label) 480 self.ticklocation = ticklocation 482 self.set_label(label) ---> 483 self._reset_locator_formatter_scale() 485 if np.iterable(ticks): 486 self.locator = ticker.FixedLocator(ticks, nbins=len(ticks)) File ~/anaconda3/lib/python3.9/site-packages/matplotlib/colorbar.py:1214, in Colorbar._reset_locator_formatter_scale(self) 1212 if self.spacing == 'uniform': 1213 funcs = (self._forward_boundaries, self._inverse_boundaries) ---> 1214 self._set_scale('function', functions=funcs) 1215 elif self.spacing == 'proportional': 1216 self._set_scale('linear') File ~/anaconda3/lib/python3.9/site-packages/matplotlib/colorbar.py:1027, in Colorbar._set_scale(self, scale, **kwargs) 1001 """ 1002 Set the colorbar long axis scale. 1003 (...) 1024 be used here. 1025 """ 1026 if self.orientation == 'vertical': ---> 1027 self.ax.set_yscale(scale, **kwargs) 1028 else: 1029 self.ax.set_xscale(scale, **kwargs) File ~/anaconda3/lib/python3.9/site-packages/matplotlib/axes/_base.py:4117, in _AxesBase.set_yscale(self, value, **kwargs) 4115 g = self.get_shared_y_axes() 4116 for ax in g.get_siblings(self): ---> 4117 ax.yaxis._set_scale(value, **kwargs) 4118 ax._update_transScale() 4119 ax.stale = True File ~/anaconda3/lib/python3.9/site-packages/matplotlib/axis.py:761, in Axis._set_scale(self, value, **kwargs) 759 def _set_scale(self, value, **kwargs): 760 if not isinstance(value, mscale.ScaleBase): ---> 761 self._scale = mscale.scale_factory(value, self, **kwargs) 762 else: 763 self._scale = value File ~/anaconda3/lib/python3.9/site-packages/proplot/scale.py:903, in _scale_factory(scale, axis, *args, **kwargs) 898 if scale not in scales: 899 raise ValueError( 900 f'Unknown axis scale {scale!r}. Options are ' 901 + ', '.join(map(repr, scales)) + '.' 902 ) ---> 903 return scales[scale](*args, **kwargs) TypeError: __init__() missing 1 required positional argument: 'transform'
使用代码
import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import get_cmap import cartopy.crs as crs import cartopy.feature as cfeature from cartopy.feature import NaturalEarthFeature from netCDF4 import Dataset from wrf import (getvar, to_np, vertcross, smooth2d, CoordPair, GeoBounds, get_cartopy, latlon_coords, cartopy_xlim, cartopy_ylim) lvl = np.arange(-10, 30, 4) lats, lons = latlon_coords(dr_nested2) ax = plt.axes(projection=crs.PlateCarree()) states = NaturalEarthFeature(category="cultural", scale="10m", facecolor="none", name="admin_1_states_provinces") ax.add_feature(states, linewidth=.4, edgecolor="black") states = NaturalEarthFeature(category="cultural", scale="10m", facecolor="none", name="admin_1_states_provinces") ax.add_feature(states, linewidth=.4, edgecolor="black") ax.coastlines('10m', linewidth=0.8) plt.contour(to_np(lons), to_np(lats), to_np(dr_nested2), 10, colors='#FF000000', transform=crs.PlateCarree()) plt.contourf(to_np(lons), to_np(lats), to_np(dr_nested2), 10, transform=crs.PlateCarree(), cmap=get_cmap("jet"),extend='both',levels=lvl) plt.colorbar(ax=ax, shrink=.98) ax.gridlines(color="black", linestyle="dotted") plt.show()
dr_nested2变量信息
array([[19.008703, 18.907665, 18.813095, ..., 21.384596, 21.471825, 21.435888], [19.123476, 18.974825, 18.839777, ..., 21.634035, 21.84276 , 21.868538], [19.16345 , 19.013046, 18.87523 , ..., 21.712034, 21.923061, 21.974125], ..., [22.84894 , 22.85399 , 22.89827 , ..., 22.873253, 22.928793, 22.977732], [22.832474, 22.79055 , 22.820337, ..., 23.111856, 23.178507, 23.201542], [22.968447, 23.084492, 23.25534 , ..., 23.269384, 23.360067, 23.377628]], dtype=float32) Coordinates: XTIME datetime64[ns] 2022-03-13 * XLAT (XLAT) float64 -25.4 -25.3 -25.2 -25.1 ... -9.0 -8.9 -8.8 -8.7 * XLONG (XLONG) float64 -75.2 -75.1 -75.0 -74.9 ... -57.8 -57.7 -57.6 -57.5 Attributes: regrid_method: patch
问题原因
报错根源是proplot库对matplotlib的刻度scale工厂做了自定义扩展,当colorbar自动设置function类型刻度时,proplot的Scale类要求必须传入transform参数,但matplotlib默认调用逻辑里没有传递该参数,导致参数缺失报错。
修复方案
方案1:显式传入mappable对象(推荐)
将contourf的返回值保存为变量,直接传给colorbar,避免自动查找时的兼容问题:
# 修改contourf部分,保存返回值 cf = plt.contourf(to_np(lons), to_np(lats), to_np(dr_nested2), 10, transform=crs.PlateCarree(), cmap=get_cmap("jet"),extend='both',levels=lvl) # 显式传入cf作为mappable plt.colorbar(cf, ax=ax, shrink=.98)
方案2:恢复matplotlib默认scale工厂
如果不需要proplot的自定义功能,可以临时覆盖回matplotlib原生的scale工厂:
import matplotlib.scale as mscale import proplot.scale # 恢复matplotlib默认的scale创建逻辑 mscale.scale_factory = mscale._scale_factory
额外优化点
代码中重复添加了两次states地理特征,可删除其中一次,减少冗余代码。
内容的提问来源于stack exchange,提问作者jnava1612
相关产品推荐
相关产品推荐

