简体   繁体   English

使用netcdf文件在python中制作填充轮廓图

[英]Making a filled contour plot in python with netcdf files

I'm attempting to make a plot emissions from a model, using Basemap and matplotlib.pyplot. 我正在尝试使用Basemap和matplotlib.pyplot从模型绘制散点图。 I'm very new to python so was attempting to use someone else's example and adjust it for my data but finding numerous errors. 我是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()

I keep getting "KeyError: 'true_lon'" and have no idea how to resolve it. 我不断收到“ KeyError:'true_lon'”,却不知道如何解决。 The data has 3 keys (lat, lon and time). 数据具有3个键(纬度,经度和时间)。 I have shown the details of the lon variable below. 我在下面显示了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

The data is global. 数据是全局的。 The details of variable I'm trying to plot (emis_all) are below. 我尝试绘制的变量(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

Any help/advice much appreciated. 任何帮助/建议,不胜感激。 Like I said I am a beginner just trying to get started and practice making a few plots with my own data. 就像我说的那样,我只是一个初学者,只是尝试开始并练习使用自己的数据作一些绘图。

The error you get is because you don't have that variable in your netCDF file. 您得到的错误是因为您的netCDF文件中没有该变量。 You should start from "the beggining" and try to figure out which does each line of your code. 您应该从“开始”开始,并尝试弄清楚代码的每一行是哪一行。 Then, select what do you actually need. 然后,选择您实际需要的内容。 I've simplified your code, just try it out: 我简化了您的代码,只需尝试一下即可:

# 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()

some usefull comands: print nc.variables will print you the list of variables of your netCDF file emi.shape will return the shape of your array. 一些有用的命令: print nc.variables将为您打印netCDF文件的变量列表emi.shape将返回数组的形状。 In my example I chose only the 1st hour (or other time lapse) of the data. 在我的示例中,我只选择了数据的第一个小时(或其他时间间隔)。 You can do everything you want with your array (like sum, mean), search for numpy module. 您可以使用数组做所有您想做的事情(例如sum,mean),搜索numpy模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM