我有以下生成绘图的代码:
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)
ax.contourf(X,Y,u)
如何添加颜色条?
我尝试了 plt.colorbar()。
要向绘图添加颜色条,您可以将
ax.contourf
调用的结果分配给变量,然后将该变量传递给 plt.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)
contour = ax.contourf(X, Y, u)
plt.colorbar(contour)
plt.show()