IndexError: too many indices for array when plot winds netcdf

IndexError: too many indices for array when plot winds 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()

在运行整个程序后,我收到错误信息................................................ ...............:[=​​13=]

**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!!!!

变量 wind_speed 有 4 个维度,您文件的 ncdump -h

short wind_speed(time, depth, latitude, longitude) ;

读作:

var = nc.variables['wind_speed'][0,:,:]

您还剩下三个维度:depth, latitude, longitude,这对于 contourf() 来说太多了。所以你需要select你想要绘制的深度,例如

cnplot = map.contourf(x, y, var[0,:,:], clevs, cmap=plt.cm.jet)