网络编程
位置:首页>> 网络编程>> Python编程>> python读取并绘制nc数据的保姆级教程

python读取并绘制nc数据的保姆级教程

作者:钢筋火龙果  发布时间:2023-11-23 02:19:24 

标签:python,读取,nc数据

 读取nc数据相关信息

#导入库
import netCDF4
from netCDF4 import Dataset

#读取数据文件
nc_file=Dataset("/media/hsy/HSYWS/001DATA/VPD_DATA/vapor_pressure_deficit_1979.nc")

#输出数据文件的两种方式
#nc_file
print(nc_file)

输出结果展示:

<class 'netCDF4._netCDF4.Dataset'> root group (NETCDF4 data model, file format HDF5): Conventions: CF-1.4

created_by: R, packages ncdf4 and raster (version 3.3-13)

date: 2021-10-08 13:21:50

dimensions(sizes): Longitude(1440), Latitude(721), Time(365)

variables(dimensions): int32 crs(), float64 Longitude(Longitude), float64 Latitude(Latitude), int32 Time(Time), float32 VPD(Time, Latitude, Longitude)

groups:

#所有变量读取
print(nc_file.variables.keys())

#输出结果:dict_keys(['crs', 'Longitude', 'Latitude', 'Time', 'VPD'])

#单个变量读取
nc_file['Longitude']
#print(nc_file.variables['Longitude'])

"""<class 'netCDF4._netCDF4.Variable'>
float64 Longitude(Longitude)
   units: degrees_east
   long_name: Longitude
unlimited dimensions:
current shape = (1440,)
filling on, default _FillValue of 9.969209968386869e+36 used"""

print(nc_file.variables['crs'])

结果输出解读:

<class 'netCDF4._netCDF4.Variable'> #文件数据类型

int32 crs()

        proj4: +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs #proj4坐标系参数,详情请见:Quick start &mdash; PROJ 9.1.0 documentation

unlimited dimensions:

current shape = () filling on, default _FillValue of -2147483647 used

#单个变量的所有属性名称
print(nc_file.variables['VPD'].ncattrs())
#['_FillValue', 'long_name', 'grid_mapping', 'proj4', 'min', 'max']
print(nc_file.variables['VPD'].proj4)#proj4坐标系
print(nc_file.variables['VPD'].grid_mapping)#给定坐标变量与真实经纬度坐标之间的映射关系:crs
print(nc_file.variables['VPD']._FillValue)#填充值或空值
#读取变量的维度
print(nc_file['VPD'].shape)
#(365, 721, 1440) (#time, latitude, longitude) 格点分辨率为:天*0.25*0.25度。
#读取变量值
VPD=nc_file.variables['VPD'][:]
print(VPD)#读取结果含有全部数值。
#print(nc_file['VPD'])#输出结果不完整

绘图

1、利用matplotlib绘图

import matplotlib.pyplot as plt
plt.contourf(long, lat, VPD[10, :, :] )
plt.colorbar(label="VPD", orientation="horizontal")
plt.show()

python读取并绘制nc数据的保姆级教程

 2、利用basemap绘图

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
lon0 = long.mean()
lat0 = lat.mean()
# 设置投影方式:cyl为圆柱投影、还可设置merc为mercator投影 llcrnrlat为起始lat;urcrnrlat为终止lat
# m = Basemap(projection='merc', llcrnrlat=lat[0], urcrnrlat=lat[-1], \
#              llcrnrlon=lon[0], urcrnrlon=lon[-1], ax=ax1)
# 参数 "resolution" 用于控制地图面积边缘的精细程度,有'l'和'h'两种取值
m = Basemap(lat_0=lat0, lon_0=lon0,projection='cyl',resolution='l')
# 绘制等经纬度线 纬度每隔20度画一条线,且标注经纬度
m.drawparallels(np.arange(-90., 91., 20.), labels=[1, 0, 0, 0], fontsize=10)
m.drawmeridians(np.arange(-180., 181., 40.), labels=[0, 0, 0, 1], fontsize=10)
m.drawcoastlines()# 绘制海岸线
lon, lat = np.meshgrid(long, lat)
xi, yi = m(lon, lat)
# cmap是图形颜色,还可选‘jet'、‘spring'、‘winter'、'summer'、'autumn'
cs = m.contourf(xi, yi, VPD[10],  cmap='summer')
# pad指位置,
cbar = m.colorbar(cs, location='bottom', pad="10%",format='%.1f')
font1 = {'family': 'DejaVu Sans', 'weight': 'normal', 'size': 16}
plt.title('VPD', font1)
plt.show()

3、利用cartopy绘图

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
proj = ccrs.PlateCarree()
fig = plt.figure(figsize=(15, 7))  
fig, ax = plt.subplots(1, 1, subplot_kw={'projection': proj})  
# 或者 ax = fig.add_subplot(111,proj=proj)
lon1 = nc_file.variables['Longitude'][:]
lat1 = nc_file.variables['Latitude'][:]
print(lon1.shape, lat1.shape)
ax.contourf(lon, lat, VPD[100])
ax.coastlines(resolution = '10m')
#添加格网
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
# 设置 gridlines 和 ticklabels
gl = ax.gridlines(draw_labels = True, linewidth = 1.5)
gl.xlabels_top = False
gl.xlines = True
gl.xformatter = LONGITUDE_FORMATTER
gl.ylabels_right = False
gl.ylines = True
gl.yformatter = LATITUDE_FORMATTER
plt.show()

python读取并绘制nc数据的保姆级教程

来源:https://blog.csdn.net/A18040554844/article/details/127654490

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com