如何为Python绘制的Contour Plot添加Colorbar?
如何给Contour Plot添加Colorbar
你直接调用plt.colorbar()失败的核心原因是:colorbar需要明确关联到contourf生成的绘图对象。ax.contourf()会返回一个QuadContourSet实例,必须把这个实例传给colorbar才能正确创建颜色条。
修正后的代码
import numpy as np import matplotlib.pyplot as plt import xarray as xr data = xr.open_dataset('mypath/data.nc') lat = np.array(data['latitude'][:]) lon = np.array(data['longitude'][:]) u = np.array(data['u'][:]) u = u.reshape(len(lat), len(lon)) fig, ax = plt.subplots(1,1,figsize=(8, 6)) X,Y = np.meshgrid(lon, lat) # 捕获contourf的返回对象 contour_plot = ax.contourf(X, Y, u) # 基于该对象创建colorbar,指定关联的轴更规范 fig.colorbar(contour_plot, ax=ax) plt.show() # 加上显示图像的语句
额外优化:利用xarray简化代码
你不需要手动把xarray数据转成numpy数组,xarray支持直接和matplotlib交互,简化后的代码如下:
import matplotlib.pyplot as plt import xarray as xr data = xr.open_dataset('mypath/data.nc') fig, ax = plt.subplots(1,1,figsize=(8, 6)) # 直接用xarray的plot方法,自动处理坐标和colorbar data['u'].plot.contourf(ax=ax) plt.show()
内容的提问来源于stack exchange,提问作者s28
相关产品推荐
相关产品推荐

