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

I am using xarray to plot a contour graph. Is there a way to not include the original colorbar but still retain the contour plot?

这是我的数据(只是来自 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, cax, ax, 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, mappable, **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, mappable, **kwargs)
   1729         cb = ColorbarPatch(cax, mappable, **kwargs)
   1730     else:
-> 1731         cb = Colorbar(cax, mappable, **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, ax, mappable, **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 方法进行很多控制,而且它接受传递给 matplotlib.

kwargs

所以你可以直接告诉 plot 使用带有 cmap 参数的特定颜色映射,你可以通过将 add_colorbar 设置为 False 来抑制颜色条本身:

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

给我: