在python中仅为感兴趣的区域绘制NETCDF数据?

2024-09-22 16:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我从netcdf文件打印数据的代码。 但是,我可以用全世界的底图绘制数据。 我通过basemap模块插入xxxxxx形状文件,我的目标是绘制到特定区域

### Import libraries###

import matplotlib.pyplot as plt 
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset
import numpy as np


### opening NETCDF dataset MERRA###

file = 'C:.../Python_Notebook/NETCDF/MERRA2_400.statD_2d_slv_Nx.20190101.nc4'
fh = Dataset(file, mode = 'r')


### Get variables ###
# Read in 'T2M' 2-meter air temperature variable.
lons = fh.variables['lon'][:] # get longitude variables
lats = fh.variables['lat'][:] # get latitude variables
tmean = fh.variables['T2MMEAN'][:,:,:] - 273.15 # get tmean variable with conversion K for °C 

### meshgrid ###

m=Basemap(projection='cyl',llcrnrlat=-20,urcrnrlat=-5,llcrnrlon=-63,urcrnrlon=-48)
lon, lat = np.meshgrid(lons, lats) # create a matrix of coordinates
xi, yi = m(lon, lat)

# Plot Data

fig,ax=plt.subplots(figsize=(20,10))
cs = m.contourf(xi,yi,np.squeeze(tmean),  cmap='rainbow') 

### Draw ### 
m.readshapefile(MTshp, name="Mt") # draw shapefile State of Mato Grosso Brazil
#m.drawcoastlines()
#m.drawcountries()
#m.drawstates()

### Draw Coordinates ###

m.drawparallels(np.arange(-80, 80, 5), labels=[1,0,0,0]) # draw parallels
m.drawmeridians(np.arange(-180, 180, 5), labels=[0,0,0,1]) # draw meridians

# Add Colorbar
cbar = m.colorbar(cs, location='right', pad="15%")
cbar.set_label('°C') # tmean units

### Labels ###
plt.xlabel('Longitude', fontweight='bold', labelpad=15)
plt.ylabel('Latitude', fontweight='bold', labelpad=25)

### Add Title ###
plt.title('01-01-2019 Mean Temperature', fontweight='bold', fontsize=12)

# Show the plot
plt.show()

如何仅在shapefile中绘制netcdf数据? 我应该做什么程序? 你能帮助我吗?请 谢谢你的理解


Tags: 数据importgetnp绘制pltnetcdfvariables