Python-地球科学-大气科学-可视化绘图系列(一)——利用xarray读取netCDF文件并画图(代码+示例)

 1 import numpy as np
 2 import xarray as xr
 3 import cartopy.crs as ccrs
 4 import cartopy.feature as cfeat
 5 from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
 6 import matplotlib.pyplot as plt
 7 
 8 
 9 ds = xr.open_dataset('2039071310.003.nc')
10 t =  ds['value']
11 lons = ds.lon.data
12 lats = ds.lat.data
13 temp = xr.DataArray(t.data.T, coords=[lats,lons], dims=['latitude','longitude'])
14 
15 # 创建画图空间
16 proj = ccrs.PlateCarree()  #创建投影
17 fig = plt.figure(figsize=(16,9))  #创建页面
18 ax = fig.subplots(1, 1, subplot_kw={'projection': proj})  #子图
19 # 设置地图属性:加载国界、海岸线、河流、湖泊
20 ax.add_feature(cfeat.BORDERS.with_scale('50m'), linewidth=0.8, zorder=1)
21 ax.add_feature(cfeat.COASTLINE.with_scale('50m'), linewidth=0.6, zorder=1)  
22 ax.add_feature(cfeat.RIVERS.with_scale('50m'), zorder=1)  
23 ax.add_feature(cfeat.LAKES.with_scale('50m'), zorder=1)  
24 # 设置网格点属性
25 gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
26   linewidth=1.2, color='k', alpha=0.5, linestyle='--')
27 gl.xlabels_top = False  #关闭顶端标签
28 gl.ylabels_right = False  #关闭右侧标签
29 gl.xformatter = LONGITUDE_FORMATTER  #x轴设为经度格式
30 gl.yformatter = LATITUDE_FORMATTER  #y轴设为纬度格式
31 # 设置colorbar
32 cbar_kwargs = {
33    'orientation': 'horizontal',
34    'label': 'Potential',
35    'shrink': 0.8,
36 }
37 # 画图
38 levels = np.arange(0,1,0.1)
39 temp.plot.contourf(ax=ax, levels=levels, cmap='Spectral_r',
40     cbar_kwargs=cbar_kwargs, transform=ccrs.PlateCarree())
41 plt.savefig('test.jpg')

示例效果(强对流概率预报结果):

 

 

你可能感兴趣的:(Python-地球科学-大气科学-可视化绘图系列(一)——利用xarray读取netCDF文件并画图(代码+示例))