使用netcdf文件在python中创建填充等高线图

时间:2015-10-22 11:44:38

标签: python matplotlib plot matplotlib-basemap

我正在尝试使用Basemap和matplotlib.pyplot从模型中进行绘图排放。我是python的新手所以试图使用别人的例子并根据我的数据进行调整,但发现了很多错误。

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

# plot rainfall from NWS using special precipitation
# colormap used by the NWS, and included in basemap.

nc = NetCDFFile('file.nc')
pm25var = nc.variables['emis_all']
data = 0.01*pm25var[:]
latcorners = nc.variables['lat'][:]
loncorners = -nc.variables['lon'][:]
lon_0 = -nc.variables['true_lon'].getValue()
lat_0 = nc.variables['true_lat'].getValue()
# create figure and axes instances
fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1,0.1,0.8,0.8])
# create polar stereographic Basemap instance.
m = Basemap(projection='stere',lon_0=lon_0,lat_0=90.,lat_ts=lat_0,\
        llcrnrlat=latcorners[0],urcrnrlat=latcorners[2],\
        llcrnrlon=loncorners[0],urcrnrlon=loncorners[2],\
        rsphere=6371200.,resolution='l',area_thresh=10000)
# draw coastlines, state and country boundaries, edge of map.
m.drawcoastlines()
m.drawstates()
m.drawcountries()
# draw parallels.
parallels = np.arange(0.,90,10.)
m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
# draw meridians
meridians = np.arange(0.,60.,10.)
m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)
ny = data.shape[0]; nx = data.shape[1]
lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid.
x, y = m(lons, lats) # compute map proj coordinates.
# draw filled contours.
clevs = [0,1,2.5,5,7.5,10,15,20,30,40,50,70,100,150,200,250,300,400,500,600,750]
cs = m.contourf(x,y,data,clevs,cmap=cm.s3pcpn)
# add colorbar.
cbar = m.colorbar(cs,location='bottom',pad="5%")
cbar.set_label('mm')
# add title
plt.title(pm25var.long_name+' for period ending '+pm25var.dateofdata)
plt.show()

我不断收到“KeyError:'true_lon'”并且不知道如何解决它。数据有3个键(lat,lon和time)。我已经在下面显示了lon变量的详细信息。

>>>print dataset.variables['lon']
<type 'netCDF4._netCDF4.Variable'>
float64 lon(lon)
long_name: longitude
units: degrees_east
comment: centre of grid cell
unlimited dimensions: 
current shape = (720,)
filling on, default _FillValue of 9.96920996839e+36 used

数据是全球性的。我试图绘制的变量(emis_all)的详细信息如下。

>>>print dataset.variables['emis_all']
<type 'netCDF4._netCDF4.Variable'>
float64 emis_all(time, lat, lon)
long_name: PM25 - Total
pollutant: PM25
sector: Total
units: kt/year
unlimited dimensions: 
current shape = (11, 360, 720)
filling on, default _FillValue of 9.96920996839e+36 used

非常感谢任何帮助/建议。就像我说的那样,我是一个初学者,只是试图开始并用我自己的数据练习制作一些情节。

1 个答案:

答案 0 :(得分:0)

您得到的错误是因为您的netCDF文件中没有该变量。你应该从开始&#34;开始&#34;并尝试找出代码的每一行。然后,选择您真正需要的是什么。我已经简化了您的代码,只需尝试一下:

# read netcdf file
nc = NetCDFFile('file.nc')
emis = nc.variables['emis_all'][:] 
lats = nc.variables['lat'][:]
lons = nc.variables['lon'][:]
nc.close()

data = emis[0,:,:] #emissions for the first hour only

# create figure and axes instances
fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1,0.1,0.8,0.8])

m = Basemap()
m.drawcoastlines()
m.drawstates()
m.drawcountries()
# draw parallels.
parallels = np.arange(0.,90,10.)
m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
# draw meridians
meridians = np.arange(0.,60.,10.)
m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)


x, y = m(lons, lats) # compute map proj coordinates.

# draw filled contours.
clevs = [0,1,2.5,5,7.5,10,15,20,30,40,50,70,100,150,200,250,300,400,500,600,750]

cs = m.contourf(x,y,data,clevs)
# add colorbar.
cbar = m.colorbar(cs,location='bottom',pad="5%")
cbar.set_label('mm')
# add title
plt.title('emissions')
plt.show()

一些有用的命令: print nc.variables会打印出netCDF文件的变量列表 emi.shape将返回数组的形状。在我的例子中,我只选择了数据的第一个小时(或其他时间间隔)。你可以用数组做所需的一切(比如sum,mean),搜索numpy模块。

相关问题