先上图片
数据是CMIP6里MIROC模式historical1979-2014年一共36年的zg数据,气候态取了36年,异常取了1979年。代码如下:
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 29 13:19:34 2024
@author: a
"""
import os
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
from cartopy.util import add_cyclic_point#去除中间白线
#from matplotlib.pyplot import MultiplelLocator
plt.rcParams['font.sans-serif'] = ['KaiTi','SimHei']
plt.rcParams['font.size']= 12
plt.rcParams['axes.unicode_minus']=False
#读取文件
path = 'C:\data\CMIP6\historical\zg'
file = os.path.join(path,'zg_day_MIROC6_*.nc')#通配符选取MIROC6模式下所有数据,共36年
fzg = xr.open_mfdataset(file)
zg = fzg['zg']
time = fzg['time']
plev = fzg['plev']
lat = fzg['lat']
lon = fzg['lon']
#选取500hPa高度
le = np.where(plev == 50000)[0]
#选取特定时间位势高度
zgti = zg.loc['1979-01-01':'1979-12-31']
#求该时间段位势高度平均
zgti_500 = zgti[:, le, :, :]
zgti_500_mean = np.nanmean(zgti_500,axis = 0)
#求总时间位势高度平均
zg_500_all = np.nanmean(zg[:, le, :, :],axis = 0)
#求异常
zg_500_ano = zgti_500_mean - zg_500_all
zg_500_ano = np.squeeze(zg_500_ano)#降维,contourf需要2D数据
#figure和ax
fig = plt.figure(figsize = (10,6), dpi = 900)
proj = ccrs.PlateCarree()
region = [0,361,-90,91]
ax = plt.axes([0.05,0.08,0.92,0.8],projection=ccrs.PlateCarree(central_longitude=180))#坐标轴位置,投影方式
ax.set_extent(region, crs = ccrs.PlateCarree())#坐标轴显示范围
#刻度设置
ax.set_xticks(np.arange(-180,181,60))#x轴
ax.set_yticks(np.arange(-90,91,30))#y轴
ax.xaxis.set_major_formatter(LongitudeFormatter())#将刻度格式转换为经纬度格式
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis = 'x', top = True, which = 'major', direction = 'in', length = 4, width = 1.5, labelsize = 10, pad = 2)
ax.tick_params(axis = 'y', right = True, which = 'major', direction = 'in', length = 4, width = 1.5, labelsize = 10, pad = 2)
plt.suptitle('1979年 500hPa位势高度异常',fontsize=15,y=0.9)
#画图
zg_500_ano1D = zg_500_ano.flatten()#降为1维方便求最值
max = max(zg_500_ano1D)
min = min(zg_500_ano1D)
zg_500_ano, lon = add_cyclic_point(zg_500_ano, coord = lon)#去中心白线
X, Y = np.meshgrid(lon,lat)#画图网格,需要先去白线,再mesh
cs = ax.contourf(X, Y, zg_500_ano,levels = np.arange(-60,61,10), cmap = plt.cm.RdBu_r)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'),lw = 0.5, color = 'k')#需要在contourf之后,不然会被填色图覆盖掉
#colorbar
l, b, w, h = 0.98, 0.2, 0.01, 0.5
rect = [l, b, w, h]
cbar_ax = fig.add_axes(rect)
cb = fig.colorbar(cs, cbar_ax, orientation = 'vertical', ticklocation = 'right',extend = 'both')
#cb.set_lable('')
cb.ax.tick_params(direction = 'in', length = 8, width = 1, labelsize = 10)
plt.savefig('C:/Users/a/Desktop/test.jpg',bbox_inches = 'tight')
plt.show()