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

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

 读取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

标签:python,读取,nc数据
0
投稿

猜你喜欢

  • python正则表达式去除两个特殊字符间的内容方法

    2023-08-24 16:22:10
  • django配置DJANGO_SETTINGS_MODULE的实现

    2023-06-18 20:14:26
  • 301转向和网址规范化

    2007-09-26 14:00:00
  • 如何利用SQL Server数据库快照形成报表

    2009-01-15 11:55:00
  • asp模块化分页源码

    2008-04-13 07:02:00
  • python 的numpy库中的mean()函数用法介绍

    2021-12-19 16:22:37
  • python脚本监控Tomcat服务器的方法

    2023-10-03 18:19:23
  • Fiddler如何抓取手机APP数据包

    2023-12-02 04:18:57
  • python实现逻辑回归的方法示例

    2021-07-27 17:04:24
  • Python自动连接ssh的方法

    2023-09-20 00:12:16
  • DOM基础教程之模型中的模型节点

    2024-06-05 09:55:35
  • Python 使用list和tuple+条件判断详解

    2022-05-13 16:36:39
  • Python基于Google Bard实现交互式聊天机器人

    2022-12-14 22:05:20
  • selenium+python 去除启动的黑色cmd窗口方法

    2023-06-07 10:56:27
  • linux下通过go语言获得系统进程cpu使用情况的方法

    2024-05-08 10:13:01
  • 详解python中的模块及包导入

    2023-12-05 08:20:16
  • node.js实现微信开发之获取用户授权

    2024-05-03 15:54:04
  • 浅谈Python中re.match()和re.search()的使用及区别

    2022-05-11 12:48:44
  • python使用正则表达式匹配字符串开头并打印示例

    2021-07-02 00:52:13
  • python实现的自动发送消息功能详解

    2021-12-09 20:45:18
  • asp之家 网络编程 m.aspxhome.com