[Python] 纯文本查看 复制代码
import cmaps
import netCDF4 as nc
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import matplotlib.patches as mpt
import numpy as np
import xarray as xr
import cartopy.feature as cf
import pandas as pd
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter,LatitudeFormatter
from cartopy.util import add_cyclic_point
import imageio
frames = []
for i in range(12):
#1、地图设置
fig =plt.figure(figsize=(8,6))
crs= ccrs.PlateCarree(central_longitude=180)
box=[-180,180,-90,90]
resolution ='50m'
xstep,ystep =60,30
ax= plt.axes(projection=crs)
#设定范围
ax.set_extent(box,crs=crs)
#附加元素(陆地、河流、湖泊)
# ax.add_feature(cfeature.LAND)
# ax.add_feature(cfeature.LAKES,alpha=0.5)
#添加河流
# ax.add_feature(cfeature.RIVERS)
#国界线
ax.add_feature (cfeature.BORDERS,linestyle=':')
#显示国界线
# ax.coastlines(resolution)
# ax.stock_img()
#2、坐标设置
ax.set_xticks(np.arange(box[0],box[1]+xstep,xstep),crs=crs)
ax.set_yticks(np.arange(box[2],box[3]+ystep,ystep),crs=crs)
#zero direction label用来设置经度的0度加不加E和w
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.coastlines('110m',lw=1,ls='--')
# ax.stock_img()
nc_obj = Dataset('hgt.mon.ltm.1991-2020.nc')
#['level', 'lat', 'lon', 'time', 'climatology_bounds', 'hgt', 'valid_yr_count']
# print(nc_obj.variables.keys())
# 3、读取数据值
#深度: level(level),,[1000. 925. 850. 700. 600. 500. 400. 300. 250. 200. 150. 100. 70. 50. 30. 20. 10.]
# print(nc_obj.variables['level'])
level = (nc_obj.variables['level'][:])
#lat(lat),[ 90. -90.]
# print(nc_obj.variables['lat'])
lat = (nc_obj.variables['lat'][:])
#lon(lon),[ 0. 357.5]
# print(nc_obj.variables['lon'])
lon= np.array(nc_obj.variables['lon'][:])-180
#hgt(time, level, lat, lon),[ -700. 35000.]
# print(nc_obj.variables['hgt'])
hgt = nc_obj.variables['hgt'][i][5]
#消除白线
hgt,lon=add_cyclic_point(hgt,coord=lon)
lon,lat=np.meshgrid(lon,lat)
#4、绘图
levels=np.arange(5000,6000,40)
levels2=np.arange(5000,6000,40)
ac1=ax.contour(lon,lat,hgt,transform=crs,levels=levels,extend='both',colors='k',linewidths=0.5)
ax.clabel(ac1,inline=True,levels=levels2,fontsize=4,fmt='%.0f')
ac2=ax.contourf(lon,lat,hgt,transform =crs,levels=levels,cmap=cmaps.matlab_jet,extend='both')
fig.colorbar(ac2,ax=ax,extend='both',shrink=0.60)
plt.rcParams['font.sans-serif']=['microsoft YaHei']
plt.rcParams['axes.unicode_minus']=False#负号
ax.set_title(str(i+1)+'月多年平均(1991-2020)500hPa高度场')
plt.savefig(str(i+1)+'月多年平均(1991-2020)500hPa高度场',dpi=300,bbox_inches = 'tight')
frames.append(imageio.imread(str(i+1)+'月多年平均(1991-2020)500hPa高度场.png'))
plt.show()
gif_name='多年平均(1991-2020)500hPa高度场.gif'
imageio.mimsave(gif_name, frames, fps=1)