我正在使用 xarray 绘制等高线图有没有办法不包含原始颜色条但仍保留等高线图?

问题描述

这是我的数据(只是一些来自 xarray 的样本数据)并制作了等高线图。但是我想制作自己的颜色条而不是使用 xarray 的嵌入颜色条。我如何让 xarray 做到这一点?

ds = xr.tutorial.open_dataset("air_temperature.nc").rename({"air": "Tair"})

# we will add a gradient field with appropriate attributes
ds["dTdx"] = ds.Tair.differentiate("lon") / 110e3 / np.cos(ds.lat * np.pi / 180)
ds["dTdy"] = ds.Tair.differentiate("lat") / 105e3
ds.dTdx.attrs = {"long_name": "$∂T/∂x$","units": "°C/m"}
ds.dTdy.attrs = {"long_name": "$∂T/∂y$","units": "°C/m"}

ds.Tair.isel(time=1).plot()
plt.show()

我尝试做 plt.colorbar(False) 但这没有用,我收到了这个错误

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-53-bcb5ae6a218e> in <module>
      8 
      9 ds.Tair.isel(time=1).plot()
---> 10 plt.colorbar(False)
     11 plt.show()

~/miniconda3/envs/py3_std_maps/lib/python3.8/site-packages/matplotlib/pyplot.py in colorbar(mappable,cax,ax,**kw)
   2176     if ax is None:
   2177         ax = gca()
-> 2178     ret = gcf().colorbar(mappable,cax=cax,ax=ax,**kw)
   2179     return ret
   2180 colorbar.__doc__ = matplotlib.colorbar.colorbar_doc

~/miniconda3/envs/py3_std_maps/lib/python3.8/site-packages/matplotlib/figure.py in colorbar(self,mappable,use_gridspec,**kw)
   2341                              'panchor']
   2342         cb_kw = {k: v for k,v in kw.items() if k not in NON_COLORBAR_KEYS}
-> 2343         cb = cbar.colorbar_factory(cax,**cb_kw)
   2344 
   2345         self.sca(current_ax)

~/miniconda3/envs/py3_std_maps/lib/python3.8/site-packages/matplotlib/colorbar.py in colorbar_factory(cax,**kwargs)
   1729         cb = ColorbarPatch(cax,**kwargs)
   1730     else:
-> 1731         cb = Colorbar(cax,**kwargs)
   1732 
   1733     cid = mappable.callbacksSM.connect('changed',cb.update_normal)

~/miniconda3/envs/py3_std_maps/lib/python3.8/site-packages/matplotlib/colorbar.py in __init__(self,**kwargs)
   1197         # Ensure the given mappable's norm has appropriate vmin and vmax set
   1198         # even if mappable.draw has not yet been called.
-> 1199         if mappable.get_array() is not None:
   1200             mappable.autoscale_None()
   1201 

AttributeError: 'bool' object has no attribute 'get_array'

解决方法

您可以使用 xarray.DataArray.plot 方法进行很多控制,而且它接受传递给 kwargsmatplotlib

因此您可以通过 plot 参数直接告诉 cmap 使用特定颜色图,并且您可以通过将 add_colorbar 设置为 False 来抑制颜色条本身:

ds.Tair.isel(time=1).plot(cmap="RdYlBu_r",add_colorbar=False)

给我:

enter image description here