import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from mpl_toolkits import basemap
filename = r'D:\\era stastics\\June.nc' #filename = r'D:\\era stastics\\biye.nc'
f = xr.open_dataset(filename)
#print(f) #time,level,lat,lon顺序
lat = f['latitude'].data #这文件的lat是递减的 time,level,lat,lon
lon = f['longitude'].data #读lon
for j in range(1,4):
Time='2022-07-{}T00:00:00.000000000'.format(int(j))
u0=f.u.sel(level=850,time=Time,latitude=lat,longitude=lon)
v0=f.v.sel(level=850,time=Time,latitude=lat,longitude=lon)
z0=f.z.sel(level=850,time=Time,latitude=lat,longitude=lon)
# t0=f.t.sel(level=500,time=Time,latitude=lat,longitude=lon)
# temp=t0-273.15 #这nc文件温度是开尔文单位,-273.15变成摄氏度单位
zz=z0/98 #这nc文件z是位势,÷98
wind = np.sqrt(u0**2 + v0**2)
select = (wind>12)
select_region = np.where(select,wind,0) #选择的地方为原风速,否则为0
fig = plt.figure()
ax = plt.axes() #创建画布
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
m = basemap.Basemap(projection="cyl",lat_0 = 0, lon_0 = 0,llcrnrlon=80,urcrnrlon=140,llcrnrlat=10,urcrnrlat=60) #采用cea投影方式
#m.drawmapboundary(fill_color='LightSkyBlue') #画边界线
m.readshapefile('D:\Code\plot\map\gadm36_CHN_1','states',drawbounds=True)
m.readshapefile('D:\Code\plot\map\gadm36_TWN_1','taiwan',drawbounds=True)
m.readshapefile('D:\Code\plot\map\九段线', '九段线', drawbounds=True,linewidth=0.8)
#m.fillcontinents(color='wheat',lake_color='LightSkyBlue')
parallels = np.arange(10.,70.,10.)
meridians = np.arange(80.,150.,10.)
m.drawparallels(parallels,labels=[True,False,False,False],linewidth=0) #画出横线,这里标签位置是左右上下,lw=0不显示网格线
m.drawmeridians(meridians,labels=[False,False,False,True],linewidth=0) #画出竖线
X, Y = np.meshgrid(lon, lat)
lonn,latt = m(X, Y)
#z_level = np.arange(520,608,8) #-->如果画500hPa用这行
#z_level = np.arange(288, 320, 4) #-->画700hPa用这行
z_level = np.arange(128,196,4) #-->画850hPa用这行
c1=ax.contour(lonn,latt,zz,levels=z_level,colors='blue',linewidths=0.8,linestyles='-')#画等高线
ax.clabel(c1)
#c2 = ax.contour(lonn, latt, zz, levels=[588], colors='blue', linewidths=1.4, linestyles='-')
#ax.clabel(c2)
#t_level=np.arange(-45,20,8)
#c2=ax.contour(lonn,latt,temp,levels=t_level,colors='red',linewidths=0.6,linestyles='-')#画等高线
#ax.clabel(c2,inline=True)
ax.barbs(lonn[::7,::7],latt[::7,::7],u0[::7,::7],v0[::7,::7],length=4,barb_increments=dict(half=7,full=13,flag=55),linewidth=0.28,flagcolor='k',ls='-',pivot='tip')#画风羽
d = ax.contourf(lonn, latt, select_region,levels=[12,15,18,21,24],cmap='PuBu',extend='max')
ax.set_title('填色区: 大于12 m/s',loc='right',fontsize=10)
plt.title("202207{:02d} 08:00 850 hPa".format(int(j)), fontsize=20, y=1.05)
plt.savefig(r"D:\\June_Aug\\07{:02d} 850hPa.png".format(int(j))) #{02d}表示2位数显示,不满足2位数则前面补零
plt.show()