IndexError:当绘制风netcdf时,数组的索引太多

时间:2017-12-02 12:53:03

标签: python matplotlib netcdf

嗨,当我尝试在matplotlib中绘制风时,我收到以下错误。

按照我的代码:

from   mpl_toolkits.basemap import Basemap, cm, shiftgrid, addcyclic
import matplotlib.pyplot as plt
from   netCDF4 import *
import numpy as np

#-- open netcdf file
nc = Dataset('/Users/Juan/Documents/python/2017112900_2017113000_daily-ifremer-L3-MWF-GLO-20171201105757-01.0.nc', mode='r')

#-- read variable
var = nc.variables['wind_speed'][0,:,:]
u10 = nc.variables['eastward_wind'][0,:,:]
v10 = nc.variables['northward_wind'][0,:,:]
lat = nc.variables['latitude'][:]
lon = nc.variables['longitude'][:]

u, lonsout = addcyclic(u10, lon)
v, lonsout = addcyclic(v10, lon)

print "lon[0]: ", lonsout[0], "lon[-1]: ", lonsout[-1]
print "lat[0]: ", lat[0], "lat[-1]: ", lat[-1]

print lonsout[:]
print lat[:]

#-- create figure and axes instances
dpi = 100
fig = plt.figure(figsize=(1100/dpi, 1100/dpi), dpi=dpi)
ax  = fig.add_axes([0.1,0.1,0.8,0.9])

#-- create map
map = Basemap(projection='cyl',llcrnrlat= -90.,urcrnrlat= 90.,\
              resolution='c',  llcrnrlon=-180.,urcrnrlon=180.)

#-- draw coastlines, state and country boundaries, edge of map
map.drawcoastlines()
map.drawstates()
map.drawcountries()

#-- create and draw meridians and parallels grid lines
map.drawparallels(np.arange( -90., 90.,30.),labels=[1,0,0,0],fontsize=10)
map.drawmeridians(np.arange(-180.,180.,30.),labels=[0,0,0,1],fontsize=10)

#-- convert latitude/longitude values to plot x/y values
#x, y = map(*np.meshgrid(lon,lat))

x, y = map(lon,lat)

#-- contour levels
clevs = np.arange(210,320,5)

#-- draw filled contours
cnplot = map.contourf(x,y,var,clevs,cmap=plt.cm.jet)


#-- add colorbar
cbar = map.colorbar(cnplot,location='bottom',pad="10%")      #-- pad: distance between map and colorbar
cbar.set_label('deg K')                                      #-- add colorbar title string

#-- transform vector and coordinate data
veclon = u10.shape[1]/2                    #-- only every 2nd vector
veclat = u10.shape[0]/2                    #-- only every 2nd vector
uproj,vproj,xx,yy = map.transform_vector(u,v,lonsout,lat,veclon,veclat,returnxy=True,masked=True)

#-- create vector plot on map
vecplot = map.quiver(xx,yy,uproj,vproj,scale=600)
qk = plt.quiverkey(vecplot, 0.2, -0.2, 20, '20 m/s', labelpos='W')  #-- position and reference label.

#-- add plot title
plt.title('Winds')

#-- display on screen
#plt.show()

运行整个程序后,收到错误消息.................................... ..........:

**IndexError: too many indices for array
        IndexErrorTraceback (most recent call last)
        <ipython-input-31-d5f74a5df99a> in <module>()
        ----> 1 cnplot = map.contourf(x,y,var,clevs,cmap=plt.cm.jet)
        /Users/Juan/anaconda/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.pyc in with_transform(self, x, y, data, *args, **kwargs)
            534             # convert lat/lon coords to map projection coords.
            535             x, y = self(x,y)
        --> 536         return plotfunc(self,x,y,data,*args,**kwargs)
            537     return with_transform
            538 
        /Users/Juan/anaconda/lib/python2.7/site-packages/mpl_toolkits/basemap/__init__.pyc in contourf(self, x, y, data, *args, **kwargs)
           3631                 # only do this check for global projections.
           3632                 if self.projection in _cylproj + _pseudocyl:
        -> 3633                     xx = x[x.shape[0]//2,:]
           3634                     condition = (xx >= self.xmin) & (xx <= self.xmax)
           3635                     xl = xx.compress(condition).tolist()
        IndexError: too many indices for array**

我不知道如何解决它。

attached my dataset for my original code!!!!

1 个答案:

答案 0 :(得分:2)

变量IBoo有4个维度,wind_speed您的文件:

  

短wind_speed(时间,深度,纬度,经度);

将其读作:

ncdump -h

您留下了三个维度:var = nc.variables['wind_speed'][0,:,:] ,这对depth, latitude, longitude来说太过分了。因此,您需要选择要绘制的深度,例如

contourf()