1.Xarray获取维度及变量信息
代码如下:
运行结果如图所示:
2.netCDF4读取nc文件
当已知维度及变量信息时,可以利用netCDF4来读取文件。
代码如下:
3.数据可视化
代码如下:
结果展示:
完整代码:
import numpy as np
from netCDF4 import Dataset
import xarray as xr
import matplotlib
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter,LatitudeFormatter
matplotlib.rcParams["font.size"]=15
scale='10m'
proj=ccrs.PlateCarree(central_longitude=180)
tran=ccrs.PlateCarree()
file1='D:\data\FIOCOM_U.2022012012-003.nc'
f1=xr.open_dataset(file1)
print(f1)
f=Dataset(file1)
lon=f.variables['xu_ocean'][:]
lat=f.variables['yu_ocean'][:]
u=f.variables['u'][0,0,:,:]
print(lon)
print(lat)
def drawglobal(x,y,z):
fig=plt.figure(figsize=(10,8))
ax=plt.subplot(111,projection=proj)
ax.add_feature(cfeature.COASTLINE.with_scale(scale),lw=0.1)
land=cfeature.NaturalEarthFeature('physical','land',scale,edgecolor='face',
facecolor=cfeature.COLORS['land'])
ax.add_feature(land,facecolor='0.75')
lon_formatter=LongitudeFormatter(zero_direction_label=False)
lat_formatter=LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
ax.set_xticks(np.arange(0,360,30),crs=tran)
ax.set_yticks(np.arange(-60,90,30),crs=tran)
ax.set_xlim(-180,180)
ax.set_ylim(-90,90)
img=ax.contourf(x,y,z,transform=tran,cmap='bwr',levels=np.arange(-1,1.1,0.2),extend='both')
cb=plt.colorbar(img,shrink=0.48)
cb.ax.tick_params(labelsize=10)
plt.xticks(fontsize=10)
plt.yticks(fontsize=10)
plt.tight_layout()
plt.show()
drawglobal(lon,lat,u)