用于等值线图的 Python 绘图颜色条

问题描述 投票:0回答:1

我有以下生成绘图的代码:

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)

Python 绘图

如何添加颜色条?

我尝试了 plt.colorbar()。

python contourf
1个回答
0
投票

要向绘图添加颜色条,您可以将

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()
© www.soinside.com 2019 - 2024. All rights reserved.