import matplotlib.pyplot as plt
import netCDF4 as nc
import numpy as np
import cartopy.mpl.ticker as cmt
import cartopy.crs as ccrs
import matplotlib.path as mpath
import cartopy.feature as cfeature
from cartopy.util import add_cyclic_point
from cartopy.mpl.ticker import (LongitudeFormatter, LatitudeFormatter)
import matplotlib as mpl
import matplotlib.ticker as mticker
import imageio.v2 as imageio
plt.rcParams['font.sans-serif']= ['Microsoft YaHei'] # 设置“微软雅黑”,图上显示出中文
plt.rcParams['axes.unicode_minus'] = False # 设置中文后,解决坐标轴上负号显示问题
frames = []
for i in range(12):
i+=1
def pa(para_month):
para_level = 200
f = nc.Dataset(r"hgt.mon.ltm.1991-2020.nc",'r')
levels = f.variables['level'][:]
lat = f.variables['lat'][:]
lon0 = f.variables['lon'][:]
time = nc.num2date(f.variables['time'][:],f.variables['time'].units).data
months = np.array([i.month for i in time])
hgt = f.variables['hgt'][:]
index_level = np.where(levels==para_level)[0][0] # 改等压面
index_month = np.where(months==para_month)[0][0] # 改月份
hgt = hgt[index_month][index_level,:,:]
hgt, lon = add_cyclic_point(hgt, coord=lon0)
Lon, Lat = np.meshgrid(lon,lat)
return Lon,Lat,hgt
Lon1,Lat1,hgt1=pa(i)
fig = plt.figure(figsize=(16,10))
proj =ccrs.PlateCarree(central_longitude=180)
#在圆柱投影中proj = ccrs.PlateCarree(central_longitude=xx)
leftlon, rightlon, lowerlat, upperlat = (-180,180,0,90)
#画0°-90°N部分
img_extent = [leftlon, rightlon, lowerlat, upperlat]
#001
ax = plt.subplot(111,projection=proj)
ax.set_extent([-180,180,-90,90], ccrs.PlateCarree())
levels = np.arange(10500,13000,100)
ec = ax.contourf(Lon1,Lat1, hgt1,cmap = 'jet',levels=levels,transform=ccrs.PlateCarree())
ac = ax.contour(Lon1,Lat1, hgt1,levels=levels,colors='black',linewidths=1,linestyles='-',transform=ccrs.PlateCarree())
#fig.colorbar(ec)
ax.clabel(ac)
g1=ax.gridlines( draw_labels=True, linewidth=1, color='gray',linestyle='--')
g1.xlocator = mticker.FixedLocator(np.linspace(-180,180,13))
g1.ylocator = mticker.FixedLocator(np.linspace(-90 ,90 ,7))
g1.xlabel_style={'size':8}
g1.ylabel_style={'size':8} # 经纬度刻度大小
ax.add_feature(cfeature.LAND)
#ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.COASTLINE)
plt.suptitle("%d月多年平均(1991-2020)200hPa高度场"%(i),fontsize='xx-large')
plt.savefig("%d月.png"%(i),dpi=200)
#plt.show()
frames.append(imageio.imread(str(i)+'月.png'))
gif_name='多年平均(1991-2020)200hPa高度场.gif'
imageio.mimsave(gif_name, frames, fps=1)