Python读取NC数据画风场和急流区
作者今天不想说话,注意点都在代码注释里了,各位看官凑活看哈。
#知识点 1.多图共用一个色标
# 2.四张一样的图做循环,不用一张一张画
#共用色标的原理,其实就是多加一个子图,把色标放子图里,然后调整一下位置就好了
#循环的原理就是建立四个子图,同样沟通步骤循环四遍
#因为四张图是一摸一样的,只有数据不同,所以通过循环4次直接产生四张图
#处理数据的包
import xarray as xr
import numpy as np
#画图的包
import matplotlib.pyplot as plt
#地图的包
import cartopy.crs as ccrs
import my_class
#打开nc文件
#这些都是只需要执行一次的东西
ds = xr.open_dataset('download_201309.nc')
lat = ds.latitude
lon = ds.longitude
time = ds.time
u = ds['u']
v = ds['v']
lat_range = lat[(lat>=22) & (lat<=44)]
lon_range = lon[(lon>=102) & (lon<=135)]
fig = plt.figure(figsize=(18,9))
#设置4个子图,并且放到列表里面,方便循环的时候用
plt.subplots_adjust(left=0.07, right=0.90, top=0.95, bottom=0.05,wspace=0.0009,hspace=0.1)
ax_a = fig.add_subplot(2,2,1,projection = ccrs.PlateCarree())
ax_b = fig.add_subplot(2,2,2,projection = ccrs.PlateCarree())
ax_c = fig.add_subplot(2,2,3,projection = ccrs.PlateCarree())
ax_d = fig.add_subplot(2,2,4,projection = ccrs.PlateCarree())
ax_list = [ax_a,ax_b,ax_c,ax_d]
abcd = ['(a)','(b)','(c)','(d)']#图右上角的abcd
i = 0#循环变量
#开始循环,以时间为循环的变量,i作为辅助
for time_i in time:
#取数据
u_region = u.sel(longitude=lon_range, latitude=lat_range,time = time_i)
v_region = v.sel(longitude=lon_range, latitude=lat_range,time = time_i)
#算风速
wind_speed = np.sqrt(u_region * u_region + v_region * v_region)
#清洗风速,小于24的都置零
e = (wind_speed > 23)
wind_speed_region = np.where(e,wind_speed,0)
#i的作用来了,利用i得到相应的子图
ax_list[i].set_xticks(np.arange(102,136,3),crs=ccrs.PlateCarree())
ax_list[i].set_yticks(np.arange(22,45,2),crs=ccrs.PlateCarree())
xticks_str = ['102', '105', '108', '111', '114', '117', '120','123', '126', '129', '132', '135°E']
ax_list[i].set_xticklabels(xticks_str,fontsize = 11)
yticks_str = ['22 ','24 ','26 ','28 ','30 ','32 ','34 ','36 ','38 ','40 ','42 ','44°N']
ax_list[i].set_yticklabels(yticks_str,fontsize = 11)
my_class.readshapefile('bou2_4l.shp',linewidth=1,ax=ax_list[i])
#填色
#色标可以自己选择风格,也可以自定义,在之前的代码里面有
cf_rh = ax_list[i].contourf(lon_range,lat_range ,wind_speed_region,cmap='hot_r',extend='both')
#风杆
ax_list[i].barbs(lon_range[::4],lat_range[::4],u_region[::4,::4],v_region[::4,::4],barbcolor=['k'],linewidth=0.5,length=5,barb_increments=dict(half=2, full=4, flag=20))
#写abcd
ax_list[i].text(0.05, 0.95, abcd[i],transform=ax_list[i].transAxes, fontsize=11)
#一次循环结束 i+1
i += 1
#色条额外添加一个子图,【左侧距离,下侧距离,宽度,高度】
position=fig.add_axes([0.90,0.3,0.01,0.4])
cb=fig.colorbar(cf_rh,cax=position,orientation='vertical')
font = {'family' : 'serif',#字体
'color' : 'k',#颜色
'weight' : 'normal',#自己百度吧
'size' : 11,#字体大小
}
cb.set_label(' m/s',rotation=360,fontdict=font)
plt.show()