├── README.md └── process_netcdf.py /README.md: -------------------------------------------------------------------------------- 1 | python-netCDF 2 | ============= 3 | 4 | # 用python的netCDF4库处理nc数据,并用basemap绘图,具体步骤如下: 5 | 6 | 7 | ## 1.导入所需要的库 8 | 9 | ```python 10 | import matplotlib.pyplot as plt 11 | plt.rc('font',family='Times New Roman',weight='normal') 12 | import matplotlib.cm as cm 13 | import matplotlib.colors 14 | import numpy as np 15 | from netCDF4 import Dataset 16 | from mpl_toolkits.basemap import Basemap 17 | import matplotlib as mpl 18 | ``` 19 | 20 | ## 2.读取nc数据,查看数据基本信息 21 | 22 | ```python 23 | fn=r'C:\Users\shaoqi_i\Desktop\E_1980_GLEAM_v31a.nc' 24 | fn_nc=Dataset(fn) 25 | 26 | print('The nc file info is:') 27 | print(fn_nc) 28 | ``` 29 | 30 | ## 3.查看数据中的所有变量 31 | ```python 32 | print("The nc file's variables are:") 33 | print(fn_nc.variables.keys()) 34 | ``` 35 | ## 4.查看数据中变量E的基本信息 36 | ```python 37 | print("E is:") 38 | summary_E=fn_nc.variables['E'] 39 | print(summary_E) 40 | 41 | ## 属性 42 | print("E's attributes are:") 43 | attributes_E=fn_nc.variables['E'].ncattrs() 44 | print(attributes_E) 45 | 46 | ## 单位 47 | print("E's units are:") 48 | units_E=fn_nc.variables['E'].units 49 | print(units_E) 50 | 51 | ## 无效值 52 | print("E's _FillValue are:") 53 | FillValue_E=fn_nc.variables['E']._FillValue 54 | print(FillValue_E) 55 | 56 | ## 名称 57 | print("E's standard_name are:") 58 | standard_name_E=fn_nc.variables['E'].standard_name 59 | print(standard_name_E) 60 | 61 | ``` 62 | 63 | ## 5.获取变量E,查看E的行列波段号 64 | 65 | > 显示为(366,1440,720),366代表1981年366天,1440是行号,720是列号 66 | ```python 67 | E=fn_nc.variables['E'] 68 | print(E.shape) 69 | 70 | ## 利用numpy的mask功能将无效值-999变成-,从而不影响后面的计算和出图 71 | E=np.ma.masked_values(E,FillValue_E) 72 | ``` 73 | 74 | ## 6.计算1981年全球的总蒸发量 75 | 76 | > axis表示按哪个坐标轴取和,366为天数,因此取0。在hdf-view里可以看到,数据的行列号是颠倒的,不是正常的全球图,因此需要矩阵转置 77 | 78 | ```python 79 | E_year=np.transpose(np.sum(E,axis=0)) 80 | print(E_year.shape) 81 | ``` 82 | 83 | ## 7.得到数据中的经度和纬度,并计算各自的最大值和最小值 84 | 85 | ```python 86 | lat=fn_nc.variables['lat'] 87 | lat_min=np.min(lat) 88 | lat_max=np.max(lat) 89 | 90 | lon=fn_nc.variables['lon'] 91 | lon_min=np.min(lon) 92 | lon_max=np.max(lon) 93 | ``` 94 | 95 | ## 8.绘图 96 | 97 | ```python 98 | ## 设置画布大小和图所占位置,subplot(1,1,1)表示画一张图,类似MATLAB里的写法 99 | plt.figure(figsize=(40,30)) 100 | plt.subplot(1,1,1) 101 | 102 | ## 设置投影类型,此处选择了两种,一种是等经纬度投影,nc数据常用;另一种是Robinson投影。 103 | ## 等经纬度投影需要设置经纬度范围,根据前面经纬度的结果取值,resolution='l',表示分辨率为低分辨率,主要是为了大陆边界展示的时候不那么突出,可设置成'h'查看一下效果 104 | 105 | m=Basemap(projection='cyl',llcrnrlon=lon_min,urcrnrlon=lon_max,llcrnrlat=lat_min,urcrnrlat=lat_max,resolution='l') 106 | 107 | ## Robinson投影,设置中心经纬度 108 | m=Basemap(projection='robin',lon_0=0,lat_0=0,resolution='l') 109 | 110 | ## 根据经纬度数组产生经纬度网格,由于经纬度都是一维数组,而E_year是二维数组,需要产生相匹配的经纬度网,从而出图。 111 | lon,lat=np.meshgrid(lon,lat) 112 | 113 | ## 将等经纬度的经纬度网格做投影转换,转换成所设定的投影 114 | lon,lat=m(lon,lat) 115 | 116 | ## 大陆边界,python自带 117 | m.drawcoastlines(linewidth=0.2) 118 | 119 | ## 经纬度网格线,包括起终点和间隔,以及label标注位置和大小,线宽,可以自己调整查看 120 | m.drawparallels(np.arange(-90, 90,30), labels=[1,0,0,0], fontsize=13,linewidth=0.8) 121 | m.drawmeridians(np.arange(-180, 180, 45), labels=[0,0,0,1], fontsize=13,linewidth=0.8) 122 | 123 | ## 颜色,jet表示红-蓝,jet_r表示颜色反向 124 | cmap = plt.cm.jet_r 125 | norm = matplotlib.colors.Normalize(vmin=-50, vmax=2100) 126 | 127 | ## (1)等值线图,20表示颜色分级,可改动查看效果 128 | cf=plt.contourf(lon,lat,E_year,20,cmap=cmap,norm=norm) 129 | 130 | ## (2)灰度图,光标在图上移动时,可以显示该点的数值,但是需要对E_year做上下颠倒处理,否则图画出来是倒的 131 | cf=m.imshow(E_year[::-1],cmap=cmap,norm=norm) 132 | 133 | ##(3)伪彩图,与等值线图相反,是渐变型 134 | cf=plt.pcolormesh(lon,lat,E_year,cmap=cmap,norm=norm) 135 | 136 | ## 标题 137 | plt.title("Global Actual Evaporation in 1980",fontsize=18) 138 | 139 | ## colorbar的位置(x,y)和参数设置(宽度,高度) 140 | cax=plt.axes([0.9, 0.11, 0.018,0.77]) 141 | cbar=plt.colorbar(cf,cax=cax) 142 | 143 | ## colorbar的数字设置,direction='in'表示黑色刻度线向里,可删掉查看效果 144 | cbar.ax.tick_params(labelsize=13, direction='in') 145 | 146 | ## colorbar的名称 147 | font = {'family' : 'Times New Roman',   148 | 'weight' : 'normal', 149 | 'size' : 15, 150 | } 151 | cbar.set_label(r'Evaporation (mm)',fontdict=font) 152 | ``` 153 | 154 | ## 9.保存输出 155 | 156 | ```python 157 | plt.savefig(r'C:\Users\shaoqi_i\Desktop\evaporation.tif',dpi=100) 158 | plt.show() 159 | ``` 160 | -------------------------------------------------------------------------------- /process_netcdf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | @author: ShaoQi(BNU 17GIS Advisor: Li Jing; NUIST 13RS Advisor: Xu YongMing) 4 | """ 5 | 6 | ############# load packages ############### 7 | import matplotlib.pyplot as plt 8 | plt.rc('font',family='Times New Roman',weight='normal') 9 | import matplotlib.cm as cm 10 | import matplotlib.colors 11 | import numpy as np 12 | from netCDF4 import Dataset 13 | from mpl_toolkits.basemap import Basemap 14 | import matplotlib as mpl 15 | 16 | ############# read netCDF file ############### 17 | fn=r'C:\Users\shaoqi_i\Desktop\E_1980_GLEAM_v31a.nc' 18 | fn_nc=Dataset(fn) 19 | 20 | ############ file info and variables ############## 21 | print('The nc file info is:') 22 | print(fn_nc) 23 | 24 | print("The nc file's variables are:") 25 | print(fn_nc.variables.keys()) 26 | 27 | ############ variable E info ############## 28 | 29 | ##### summary ##### 30 | print("E is:") 31 | summary_E=fn_nc.variables['E'] 32 | print(summary_E) 33 | 34 | ##### attributes ##### 35 | print("E's attributes are:") 36 | attributes_E=fn_nc.variables['E'].ncattrs() 37 | print(attributes_E) 38 | 39 | ##### units ##### 40 | print("E's units are:") 41 | units_E=fn_nc.variables['E'].units 42 | print(units_E) 43 | 44 | ##### FillValue ##### 45 | print("E's _FillValue are:") 46 | FillValue_E=fn_nc.variables['E']._FillValue 47 | print(FillValue_E) 48 | 49 | ##### standard_name ##### 50 | print("E's standard_name are:") 51 | standard_name_E=fn_nc.variables['E'].standard_name 52 | print(standard_name_E) 53 | 54 | ############# get E variable ############### 55 | E=fn_nc.variables['E'] 56 | print(E.shape) 57 | 58 | ############# mask fillvalues ############### 59 | E=np.ma.masked_values(E,FillValue_E) 60 | 61 | ############# calculate 1981 evapration all days ############### 62 | E_year=np.transpose(np.sum(E,axis=0)) 63 | print(E_year.shape) 64 | 65 | ############# get lat variable and lat_min, lat_max ############### 66 | lat=fn_nc.variables['lat'] 67 | lat_min=np.min(lat) 68 | lat_max=np.max(lat) 69 | 70 | ############# get lon variable and lon_min, lon_max ###############a 71 | lon=fn_nc.variables['lon'] 72 | lon_min=np.min(lon) 73 | lon_max=np.max(lon) 74 | 75 | ############# plot ############### 76 | plt.figure(figsize=(40,30)) 77 | plt.subplot(1,1,1) 78 | 79 | ############# set projection ############### 80 | 81 | ##### geographic projection ##### 82 | m=Basemap(projection='cyl',llcrnrlon=lon_min,urcrnrlon=lon_max,llcrnrlat=lat_min,urcrnrlat=lat_max,resolution='l') 83 | 84 | ##### Robinson projection ##### 85 | m=Basemap(projection='robin',lon_0=0,lat_0=0,resolution='l') 86 | 87 | ##### generate lon and lat grid ##### 88 | lon,lat=np.meshgrid(lon,lat) 89 | 90 | ##### exchange the lon and lat into the projection lon and lat ##### 91 | lon,lat=m(lon,lat) 92 | 93 | ##### plot the continent lines ##### 94 | m.drawcoastlines(linewidth=0.2) 95 | 96 | ##### plot the lon and lat lines ##### 97 | m.drawparallels(np.arange(-90, 90,30), labels=[1,0,0,0], fontsize=13,linewidth=0.8) 98 | m.drawmeridians(np.arange(-180, 180, 45), labels=[0,0,0,1], fontsize=13,linewidth=0.8) 99 | 100 | ##### set colorbar ##### 101 | cmap = plt.cm.jet_r 102 | norm = matplotlib.colors.Normalize(vmin=-50, vmax=2100) 103 | 104 | ##### plot the data ##### 105 | ##### contour plot ##### 106 | #cf=plt.contourf(lon,lat,E_year,20,cmap=cmap,norm=norm) 107 | 108 | ##### show values ##### 109 | #cf=m.imshow(E_year[::-1],cmap=cmap,norm=norm) 110 | 111 | ##### mesh ##### 112 | cf=plt.pcolormesh(lon,lat,E_year,cmap=cmap,norm=norm) 113 | 114 | ##### set the title ##### 115 | plt.title("Global Actual Evaporation in 1980",fontsize=18) 116 | 117 | ##### plot the colorbar ##### 118 | ##### colorbar location x,y and width,height ##### 119 | cax=plt.axes([0.9, 0.11, 0.018,0.77]) 120 | cbar=plt.colorbar(cf,cax=cax) 121 | 122 | ##### colorbar ticklabels ##### 123 | cbar.ax.tick_params(labelsize=13, direction='in') 124 | 125 | ##### colorbar label ###### 126 | font = {'family' : 'Times New Roman', 127 | 'weight' : 'normal', 128 | 'size' : 15, 129 | } 130 | cbar.set_label(r'Evaporation (mm)',fontdict=font) 131 | 132 | ##### save the figure ##### 133 | plt.savefig(r'C:\Users\shaoqi_i\Desktop\evaporation.tif',dpi=100) 134 | 135 | ##### show the plot ##### 136 | plt.show() 137 | --------------------------------------------------------------------------------