Beispiel #1
0
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# set desired contour levels.
clevs = p.arange(960,1061,5)
# compute native x,y coordinates of grid.
x, y = m(lons, lats)
# define parallels and meridians to draw.
parallels = p.arange(-80.,90,20.)
meridians = p.arange(0.,360.,20.)
# number of repeated frames at beginning and end is n1.
nframe = 0; n1 = 10
l,b,w,h=ax.get_position()
# loop over times, make contour plots, draw coastlines, 
# parallels, meridians and title.
for nt,date in enumerate(datelabels[1:]):
    CS = m.contour(x,y,slp[nt,:,:],clevs,linewidths=0.5,colors='k',animated=True)
    CS = m.contourf(x,y,slp[nt,:,:],clevs,cmap=p.cm.RdBu_r,animated=True)
    # plot wind vectors on lat/lon grid.
    # rotate wind vectors to map projection coordinates.
    #urot,vrot = m.rotate_vector(u[nt,:,:],v[nt,:,:],lons,lats)
    # plot wind vectors over map.
    #Q = m.quiver(x,y,urot,vrot,scale=500) 
    # plot wind vectors on projection grid (looks better).
    # first, shift grid so it goes from -180 to 180 (instead of 0 to 360
    # in longitude).  Otherwise, interpolation is messed up.
    ugrid,newlons = shiftgrid(180.,u[nt,:,:],longitudes,start=False)
    vgrid,newlons = shiftgrid(180.,v[nt,:,:],longitudes,start=False)
    # transform vectors to projection grid.
    urot,vrot,xx,yy = m.transform_vector(ugrid,vgrid,newlons,latitudes,51,51,returnxy=True,masked=True)
    # plot wind vectors over map.
    Q = m.quiver(xx,yy,urot,vrot,scale=500)
    # make quiver key.
Beispiel #2
0
mapfile = sys.argv[1]+'.lonlatT'
lonfile = sys.argv[1]+'.lon'
latfile = sys.argv[1]+'.lat'
color_num = int(sys.argv[2])

# load data
map=array(load(mapfile))
lons=array(load(lonfile))
lats=array(load(latfile))
map,lons = shiftgrid(180.,map,lons,start=False)

# Mollweide projection
m1 = Basemap(projection='moll',lon_0=0.5*(lons[0]+lons[-1]))
lons, lats = meshgrid(lons, lats)
fig1 = m1.createfigure()
x, y = m1(lons, lats)
cs = m1.contourf(x,y,map,color_num,cmap=cm.jet)
m1.drawparallels(arange(-90.,90.,20.),labels=[1,0,0,0])
m1.drawmeridians(arange(0.,420.,30.),labels=[0,0,0,1])
#title('Moll. proj:'+ sys.argv[1])
title(r'$>3\sigma\/ detections\/ composite\/ map:\/ skewness$')
#title(r'$>3\sigma\/ detections\/ composite\/ map:\/ kurtosis$')
colorbar();

savefig(sys.argv[1]+'-moll.png'); #savefig(sys.argv[1]+'-moll.eps')
savefig(sys.argv[1]+'-moll.jpg');


#show()
Beispiel #3
0
m.drawstates()
m.drawcountries()
# draw parallels.
delat = 10.0
parallels = pylab.arange(0.,90,delat)
m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
# draw meridians
delon = 10.
meridians = pylab.arange(180.,360.,delon)
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)
# new axis for colorbar.
l,b,w,h=ax.get_position()
cax = pylab.axes([l+w+0.025, b, 0.025, h]) # setup colorbar axes
# draw colorbar.
pylab.colorbar(cs, cax, format='%g', ticks=clevs, drawedges=False) 
pylab.axes(ax)  # make the original axes current again
# plot title
pylab.title(plottitle+'- contourf',fontsize=10)

pylab.subplot(212)
ax = pylab.gca()
# draw coastlines, state and country boundaries, edge of map.
m.drawcoastlines()
m.drawstates()
m.drawcountries()
Beispiel #4
0
fig = m1.createfigure()
subplots_adjust(left=0, right=.99, top=0.99, bottom=0.1, wspace=0, hspace=0)
x, y = m1(lons, lats)

fig = figure(figsize=(12, 6), dpi=dpires)
#fig=figure(figsize=(4,2), dpi=dpires)
#print dpires
ax = gca()

#cs = m1.contourf(x,y,mapM,color_num,cmap=cm.jet)
#cs = m1.contourf(x,y,mapM,color_num,cmap=palette, norm = matplotlib.colors.normalize(vmin=minv, vmax=maxv, clip=False) )
#cs = m1.contourf(x,y,mapM,colors=None, cmap=palette, norm = matplotlib.colors.normalize(vmin=minv, vmax=maxv, clip=False) )
#cs = m1.contourf(x,y,mapM, color_num, cmap=palette, norm = matplotlib.colors.normalize(vmin=minv, vmax=maxv, clip=False), extend='min' )
#cs = m1.contourf(x,y,mapM, levels, cmap=palette, norm = matplotlib.colors.normalize(vmin=minv, vmax=maxv, clip=False) )
cs = m1.contourf(x, y, mapM, levels, cmap=palette)

#cs = m1.imshow(mapM, cmap=palette, norm = matplotlib.colors.normalize(vmin=minv, vmax=maxv, clip=False) )

m1.drawmapboundary(color='k', linewidth=1.0, ax=None)
#cs = m1.contourf(x,y,mapM, cmap=palette, norm = colors.normalize(vmin=-2, vmax=2, clip=False) )
#im = imshow(mapM, interpolation='bilinear',    cmap=palette,    norm = colors.normalize(vmin = -1.0, vmax = 1.0, clip = False),    origin='lower', extent=[-3,3,-3,3])
#cs = imshow(mapM, cmap=palette, norm = colors.normalize(vmin=minv, vmax=maxv, clip=False) )

# EXPERIMENTAL BEGIN
#s='nofile'
#mapfile = s+'.lonlatT'
#lonfile = s+'.lon'
#latfile = s+'.lat'
#map=array(load(mapfile))
#lons=array(load(lonfile))
Beispiel #5
0
print max(ravel(spd))
udat, vdat, xv, yv = m.transform_vector(u,v,lons,lats,nxv,nyv,returnxy=True)
pdat, xp, yp = m.transform_scalar(p,lons,lats,nxp,nyp,returnxy=True)

print min(ravel(udat)),max(ravel(udat))
print min(ravel(vdat)),max(ravel(vdat))
print min(ravel(pdat)),max(ravel(pdat))
spd = sqrt(udat**2+vdat**2)
print max(ravel(spd))

# setup figure with same aspect ratio as map.
xsize = rcParams['figure.figsize'][0]
fig=figure(figsize=(xsize,m.aspect*xsize))
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# plot filled contours over map
levels, colls = m.contourf(xp,yp,pdat,15,cmap=cm.jet,colors=None)
# plot wind vectors over map.
m.quiver(xv,yv,udat,vdat)
cax = axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes.
colorbar(tickfmt='%d', cax=cax) # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
m.drawcountries()
# draw parallels
delat = 20.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles,labels=[1,1,1,1])
# draw meridians
delon = 45.
meridians = arange(-180,180,delon)
Beispiel #6
0
etopo = topodict['data']
lons = topodict['lons']
lats = topodict['lats']
# create figure.
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_axes([0.125, 0.175, 0.75, 0.75], frameon=False)
# create Basemap instance for Robinson projection.
# set 'ax' keyword so pylab won't be imported.
m = Basemap(projection='robin', lon_0=0.5 * (lons[0] + lons[-1]), ax=ax)
# reset figure size to have same aspect ratio as map.
# fig will be 8 inches wide.
fig.set_figsize_inches((8, m.aspect * 8.))
# make filled contour plot.
x, y = m(*meshgrid(lons, lats))
levels, colls = m.contourf(x, y, etopo, 30, cmap=cm.jet, colors=None)
# draw coastlines.
m.drawcoastlines()
# draw a line around the map region.
m.drawmapboundary()
# draw parallels and meridians.
m.drawparallels(nx.arange(-60., 90., 30.), labels=[1, 0, 0, 0], fontsize=10)
m.drawmeridians(nx.arange(0., 420., 60.), labels=[0, 0, 0, 1], fontsize=10)
# add a title.
ax.set_title('Robinson Projection')
# add a colorbar.
cax = fig.add_axes([0.25, 0.05, 0.5, 0.05], frameon=False)
fig.colorbar(colls.mappable, cax=cax, tickfmt='%d', orientation='horizontal')
# save image (width 800 pixels with dpi=100 and fig width 8 inches).
canvas.print_figure('simpletest', dpi=100)
# done.
Beispiel #7
0
parallels = pylab.arange(0., 90, delat)
m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
# draw meridians
delon = 10.
meridians = pylab.arange(180., 360., delon)
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)
# new axis for colorbar.
l, b, w, h = ax.get_position()
cax = pylab.axes([l + w + 0.025, b, 0.025, h])  # setup colorbar axes
# draw colorbar.
pylab.colorbar(cs, cax, format='%g', ticks=clevs, drawedges=False)
pylab.axes(ax)  # make the original axes current again
# plot title
pylab.title(plottitle + '- contourf', fontsize=10)

pylab.subplot(212)
ax = pylab.gca()
# draw coastlines, state and country boundaries, edge of map.
m.drawcoastlines()
m.drawstates()
m.drawcountries()
Beispiel #8
0
            resolution='c',
            area_thresh=10000.,
            projection='npstere')
# create a figure, add an axes.
fig = figure(figsize=(8, 8))
ax = fig.add_axes([0.1, 0.1, 0.7, 0.7])
# rotate wind vectors to map projection coordinates.
# (also compute native map projections coordinates of lat/lon grid)
# only do Northern Hemisphere.
urot, vrot, x, y = m.rotate_vector(u[36:, :],
                                   v[36:, :],
                                   lons[36:, :],
                                   lats[36:, :],
                                   returnxy=True)
# plot filled contours over map.
cs = m.contourf(x, y, p[36:, :], 15, cmap=cm.jet)
# plot wind vectors over map.
Q = m.quiver(x, y, urot, vrot)  #or specify, e.g., width=0.003, scale=400)
qk = quiverkey(Q, 0.95, 1.05, 25, '25 m/s', labelpos='W')
cax = axes([0.875, 0.1, 0.05, 0.7])  # setup colorbar axes.
colorbar(cax=cax)  # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
m.drawcountries()
# draw parallels
delat = 20.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles, labels=[1, 1, 1, 1])
# draw meridians
delon = 45.
Beispiel #9
0
		cdict = {'red': ((0.,)*3,(.5,1.,1.),(1.,1.,1.)),
			'green': ((0.,)*3,(.5,1.,1.),(1.,0.,0.)),
			'blue': ((0.,1.,1.),(.5,1.,1.),(1.,0.,0.))}
		return matplotlib.colors.LinearSegmentedColormap('bwr',cdict,256)

	figure(figsize=(8,8))
	subplot(ncol,nrow,nslice)
	for i in xrange(nslice):
		lon = composites.getLongitude()
		lat = composites.getLatitude()
		xx,yy = meshgrid(lon,lat)
		m = Basemap(resolution='l',lat_0=N.average(lat),lon_0=N.average(lon),
			llcrnrlon=min(lon),llcrnrlat=min(lat),
			urcrnrlon=max(lon),urcrnrlat=max(lat))
		levels = vcs.mkscale(genutil.minmax(composites))
		m.contourf(lon,lat,composites[i],levels=levels,cmap=bwr)
		clabel(m.contour(lon,lat,composites[i],levels=levels))
		title("Phase %i/%i" (i+1,6))
		m.drawcoastlines()
		m.drawcountries()
		m.fillcontinents(color='coral')
		m.drawparallels(vcs.mkscale(genutil.minmax(lat)),labels=[1,0,0,0])
		m.drawmeridians(vcs.mkscale(genutil.minmax(lon)),labels=[0,0,0,1])
	figtext(.5,1.,"\n%s [%s]" % ("El Nino phase composites\nSea surface temperature", composites.units))
	savefig(sys.argv[0].replace(".py",".png"))
	show()
	

# Fall back to vcs because we have it!
except:
	# Plot 1 phase over two, then a time series
Beispiel #10
0
def plot_ncdf_output(id, datafn, **kwds):
    """Plot model field id from the data in netCDF file datafn.

    Positional Input Parameter:
    * id:  Name of the id of the field to plot.  String.

    * datafn:  Filename containing the output data to plot.  String.

    Input keyword parameter descriptions are found in the docstring
    for Qtcm methods ploti, plotm, and other methods that call this
    private method.  In general, those methods take the keyword
    parameters they receive and pass it along unchanged as keyword
    parameters to this function.  In that sense, this function is
    seldom used as a stand-alone function, but rather is usually
    used coupled with a Qtcm instance.

    The data fields read in from the netCDF output file are dimensioned
    (time, lat, lon).  This is different than how the data is stored
    in the compiled QTCM model fields (lon, lat, time), and at the
    Python level (lon, lat).  The reason this is the case is that
    f2py automatically makes the arrays passed between the Python
    and Fortran levels match.

    For a lat vs. lon plot, the contour plot is superimposed onto
    a cylindrical projection map of the Earth with continents drawn
    and labeled meridians and parallels.  The title also includes
    the model time, and x- and y-axis labels are not drawn.

    All numerical data used for plotting come from the netCDF output
    file for consistency (e.g., the dimensions of u1).  Currently
    this method only works for 3-D data arrays (two in space, one
    in time).
    """
    #- Accomodate other ids.  The id that this routine will use
    #  (i.e., iduse corresponds to the name in the netCDF output file)
    #  is called iduse.  Set this to id, except for the case where
    #  some aliases of ids are entered in which iduse is the alias:

    if id == 'Qc': iduse = 'Prec'
    elif id == 'FLWut': iduse = 'OLR'
    elif id == 'STYPE': iduse = 'stype'
    else: iduse = id


    #- Set defined keyword defaults.  All are set to None except for
    #  nlatlon which gets an integer:

    plotkwds_ids = ['lat', 'lon', 'time', 'fn', 'levels', 'title',
                    'xlabel', 'ylabel', 
                    'filled', 'nlatlon', 'tmppreview']

    plotkwds = {}
    for ikey in plotkwds_ids:
        if kwds.has_key(ikey):
            plotkwds[ikey] = copy.copy(kwds[ikey])
        else:
            plotkwds[ikey] = None

    if not kwds.has_key('nlatlon'):
        plotkwds['nlatlon'] = 8


    #- Get data and dimensions of iduse to plot:

    fileobj = S.NetCDFFile(datafn, mode='r')
    data = N.array(fileobj.variables[iduse].getValue())
    data_name = fileobj.variables[iduse].long_name
    data_units = fileobj.variables[iduse].units

    dim = {}
    dimname = {}
    dimunits = {}

    dim['lat'] = N.array(fileobj.variables['lat'].getValue())
    dimname['lat'] = fileobj.variables['lat'].long_name
    dimunits['lat'] = fileobj.variables['lat'].units

    dim['lon'] = N.array(fileobj.variables['lon'].getValue())
    dimname['lon'] = fileobj.variables['lon'].long_name
    dimunits['lon'] = fileobj.variables['lon'].units
    
    dim['time'] = N.array(fileobj.variables['time'].getValue())
    dimname['time'] = fileobj.variables['time'].long_name
    dimunits['time'] = fileobj.variables['time'].units

    fileobj.close()


    #- Alter data long name to remove any units.  The definition
    #  of units as the substring within the [] is the same as used in
    #  defVar in output.F90 of the compiled QTCM model.  Remove 
    #  underscores and extra whitespace in data_name and data_units, 
    #  replacing with a single whitespace character between words:

    idx1 = data_name.find('[')
    idx2 = data_name.find(']')
    if idx1 != -1 and idx2 != -1:
        data_name = data_name[:idx1] + data_name[idx2+1:]
    data_name = data_name.strip()

    data_name  = ' '.join(data_name.replace('_',' ').split())
    data_units = ' '.join(data_units.replace('_',' ').split())


    #- Alter dimension long name to remove any units.  The definition
    #  of units as the substring within the [] is the same as used in
    #  defVar in output.F90 of the compiled QTCM model.  Remove 
    #  underscores and extra whitespace in name and units, replacing 
    #  with a single whitespace character between words, and 
    #  capitalizing like a title:

    for idimkey in dim.keys():
        idimname = dimname[idimkey]
        idx1 = idimname.find('[')
        idx2 = idimname.find(']')
        if idx1 != -1 and idx2 != -1:
            idimname = idimname[:idx1] + idimname[idx2+1:]
        dimname[idimkey] = idimname.strip()

        dimname[idimkey]  = \
            ' '.join(dimname[idimkey].replace('_',' ').split()).title()
        dimunits[idimkey] = \
            ' '.join(dimunits[idimkey].replace('_',' ').split()).title()


    #- Some data checks:

    if N.rank(data) != 3:
        raise ValueError, '_plot: can only plot lat, lon, time fields'
    if not N.allclose(dim['time'], N.sort(dim['time'])):
        raise ValueError, '_plot: time not monotonically ascending'
    if not N.allclose(dim['lat'], N.sort(dim['lat'])):
        raise ValueError, '_plot: lat not monotonically ascending'
    if not N.allclose(dim['lon'], N.sort(dim['lon'])):
        raise ValueError, '_plot: lon not monotonically ascending'
    if N.shape(data)[0] != N.size(dim['time']):
        raise ValueError, '_plot: data time dim mismatch'
    if N.shape(data)[1] != N.size(dim['lat']):
        raise ValueError, '_plot: data lat dim mismatch'
    if N.shape(data)[2] != N.size(dim['lon']):
        raise ValueError, '_plot: data lon dim mismatch'


    #- Choose and describe ranges for lat, lon, and time.  The
    #  section cycles through the dictionary of dimensions.  idim is
    #  the 1-D array of the values of that dimension.  rngs is a
    #  dictionary where each entry corresponds to a dimension, and the
    #  value of the entry is the values of that dimension that are to 
    #  be plotted.  rngs_idxs are the indices in the original 
    #  dimensions array corresponding to the values in rngs.  
    #  keys_rngs_sizes_gt_1 is a list of the keys of ranges that have 
    #  sizes greater than 1:

    rngs = {}
    rngs_idxs = {}
    keys_rngs_sizes_gt_1 = []
    for idimkey in dim.keys():
        idim = dim[idimkey]

        if plotkwds[idimkey] == None:
            dim_mask = N.ones( N.size(idim), dtype=int )

        elif N.isscalar(plotkwds[idimkey]):
            dim_mask = where_close( idim, plotkwds[idimkey] )
            if N.sum(dim_mask) != 1:
                raise ValueError, 'no point chosen'

        elif (not N.isscalar(plotkwds[idimkey])) and \
             N.size(plotkwds[idimkey]) == 1:
            dim_mask = where_close( idim, plotkwds[idimkey][0] )
            if N.sum(dim_mask) != 1:
                raise ValueError, 'no point chosen'

        elif N.size(plotkwds[idimkey]) == 2:
            dim_mask = N.logical_and( idim >= plotkwds[idimkey][0],
                                      idim <= plotkwds[idimkey][-1] )

        else:
            raise ValueError, 'bad dimension range keyword entry'

        rngs[idimkey]      = N.compress( dim_mask, idim )
        rngs_idxs[idimkey] = N.compress( dim_mask, N.arange(N.size(idim)) )
        if N.size(rngs[idimkey]) > 1:
            keys_rngs_sizes_gt_1.append(idimkey)


    #- Set plot types (line or contour):

    if len(keys_rngs_sizes_gt_1) == 0:
        raise ValueError, 'cannot plot without any fixed dimension'
    elif len(keys_rngs_sizes_gt_1) == 1:
        plottype = 'line'
    elif len(keys_rngs_sizes_gt_1) == 2:
        plottype = 'contour'
    else:
        raise ValueError, 'cannot plot with > 2 varying dimensions'


    #- Set plot axis fields and axis names, depending on what sort
    #  of dimensions will be plotted.  If lon is to be plotted, it is
    #  always the x-axis.  If lat is to be plotted, it is always the
    #  y-axis.  In this section and later on in a few places, I
    #  rely on the count method for a list as a Boolean test:  If it
    #  returns 0, consider that False; > 0 is True.  The text for the
    #  title and axis labels to be passed to the xlabel, etc. methods,
    #  are called titlename, xname, and yname:

    if plottype == 'line':                       #+ Choose x-axis vector and
        x = rngs[keys_rngs_sizes_gt_1[0]]        #  x/y names for line plot
        xname = dimname[keys_rngs_sizes_gt_1[0]] + ' [' \
              + dimunits[keys_rngs_sizes_gt_1[0]] + ']'
        yname = data_name + ' [' + data_units + ']'

    elif plottype == 'contour':                  #+ Choose axis vectors and
        if keys_rngs_sizes_gt_1.count('lon'):    #  names for contour plot
            x = rngs['lon']
            xname = dimname['lon'] + ' [' + dimunits['lon'] + ']'
        if keys_rngs_sizes_gt_1.count('lat'):
            y = rngs['lat']
            yname = dimname['lat'] + ' [' + dimunits['lat'] + ']'
        if keys_rngs_sizes_gt_1.count('time'):
            if keys_rngs_sizes_gt_1.count('lon'):
                y = rngs['time']
                yname = dimname['time'] + ' [' + dimunits['time'] + ']'
            elif keys_rngs_sizes_gt_1.count('lat'):
                x = rngs['time']
                xname = dimname['time'] + ' [' + dimunits['time'] + ']'
            else:
                raise ValueError, 'bad treatment of time'

    else:
        raise ValueError, 'unrecognized plottype'


    #- Override xname, yname, and titlename with keywords, if they
    #  are not None.  titlename receives data_name and data_units
    #  by default:

    if plotkwds['xlabel'] != None:
        xname = plotkwds['xlabel']
    if plotkwds['ylabel'] != None:
        yname = plotkwds['ylabel']

    if plotkwds['title'] != None:
        titlename = plotkwds['title']
    else:
        titlename = data_name + ' [' + data_units + ']'


    #- Pick data to be plotted and plot:

    pylab.clf()                       #+ Clear any previous figures
    pylab.figure(1)                   #+ Open a pylab figure

    if plottype == 'line':            #+ Select data for a line plot
        y = data[rngs_idxs['time'],   #  and plot
                 rngs_idxs['lat'], 
                 rngs_idxs['lon']]
        pylab.plot(x, y)

    elif plottype == 'contour':       #+ Select data for a contour
        ritim = rngs_idxs['time']     #  plot and plot
        rilat = rngs_idxs['lat']
        rilon = rngs_idxs['lon']


        #* Extract subarrays depending on which two dimensions are 
        #  chosen:

        if N.size(rngs_idxs['time']) == 1:
            zgrid = num.MLab.squeeze(data[ ritim[0],
                                           rilat[0]:rilat[-1]+1, 
                                           rilon[0]:rilon[-1]+1 ])
        elif N.size(rngs_idxs['lat']) == 1:
            zgrid = num.MLab.squeeze(data[ ritim[0]:ritim[-1]+1,
                                           rilat[0],
                                           rilon[0]:rilon[-1]+1 ])
        elif N.size(rngs_idxs['lon']) == 1:
            zgrid = num.MLab.squeeze(data[ ritim[0]:ritim[-1]+1,
                                           rilat[0]:rilat[-1]+1, 
                                           rilon[0] ])
        else:
            raise ValueError, 'unrecognized configuration'


        #* Change zgrid for special case of a lat. vs. time contour 
        #  plot.  Calculate xgrid and ygrid:

        if keys_rngs_sizes_gt_1.count('time') and \
           keys_rngs_sizes_gt_1.count('lat'):
           zgrid = N.transpose(zgrid)

        xgrid, ygrid = pylab.meshgrid(x, y)
        

        #* Set contour levels:

        if plotkwds['levels'] == None:
            levels = nice_levels(zgrid)
        else:
            levels = plotkwds['levels']


        #- Plot (creating continents first if is a lat vs. lon plot)
        #  and write contour levels/color bar as appropriate:

        if keys_rngs_sizes_gt_1.count('lon') and \
           keys_rngs_sizes_gt_1.count('lat'):
            mapplot = Basemap(projection='cyl', resolution='l',
                              llcrnrlon=N.min(xgrid), llcrnrlat=N.min(ygrid),
                              urcrnrlon=N.max(xgrid), urcrnrlat=N.max(ygrid))
            mapplot.drawcoastlines()
            mapplot.drawmeridians(nice_levels(rngs['lon'], 
                                  approx_nlev=plotkwds['nlatlon']),
                                  labels=[1,0,0,1])
            mapplot.drawparallels(nice_levels(rngs['lat'],
                                  approx_nlev=plotkwds['nlatlon']),
                                  labels=[1,0,0,1])
            if plotkwds['filled']:
                plot = mapplot.contourf(xgrid, ygrid, zgrid, levels)
                pylab.colorbar(plot, orientation='horizontal', format='%g')
            else:
                plot = mapplot.contour(xgrid, ygrid, zgrid, levels)
                pylab.clabel(plot, inline=1, fontsize=10, fmt='%g')
        else:
            if plotkwds['filled']:
                plot = pylab.contourf(xgrid, ygrid, zgrid, levels)
                pylab.colorbar(plot, orientation='horizontal', format='%g')
            else:
                plot = pylab.contour(xgrid, ygrid, zgrid, levels)
                pylab.clabel(plot, inline=1, fontsize=10, fmt='%g')

    else:
        raise ValueError, 'unrecognized plottype'


    #- Add titling.  Lat vs. lon plots do not have axis labels because
    #  the map labels already make it clear, and for those plots the
    #  title also includes the time value:

    if keys_rngs_sizes_gt_1.count('lon') and \
       keys_rngs_sizes_gt_1.count('lat'):
        titlename = titlename + ' at ' \
                  + dimname['time'] + ' ' \
                  + str(rngs['time'][0]) + ' ' \
                  + dimunits['time']
        titlename = mpl_latex_script1(titlename)
        pylab.title(titlename)
    else: 
        titlename = mpl_latex_script1(titlename)
        xname = mpl_latex_script1(xname)
        yname = mpl_latex_script1(yname)
        pylab.xlabel(xname)
        pylab.ylabel(yname)
        pylab.title(titlename)


    #- Output plot to PNG file or screen.  The show command seems to
    #  have a problem on my Mac OS X, so save to a temporary file
    #  and use preview to view for fn == None and tmppreview set to
    #  True.  Note that the temporary file is not deleted by this 
    #  method:

    if plotkwds['fn'] == None:                       #+ Screen display
        if plotkwds['tmppreview'] and sys.platform == 'darwin':
            outputfn = tempfile.mkstemp('.png','qtcm_')
            pylab.savefig(outputfn[-1])
            os.system('open -a /Applications/Preview.app '+outputfn[-1])
        else:
            pylab.show()

    elif type(plotkwds['fn']) == type('a'):          #+ Write to file
        pylab.savefig(plotkwds['fn'])
        pylab.close(1)

    else:
        raise ValueError, 'cannot write to this type of file'
Beispiel #11
0
#plots = ['contour','imshow']

for np,plot in enumerate(plots):

    fig.add_subplot(1,2,np+1)
    ax = gca()

    # plot data.
    print plot+' plot ...'
    if plot == 'pcolor':
        m.pcolor(x,y,hgt,shading='flat')
    elif plot == 'imshow':
        im = m.imshow(hgt)
    elif plot == 'contour':
        levels, colls = m.contour(x,y,hgt,15,linewidths=0.5,colors='k')
        levels, colls = m.contourf(x,y,hgt,15,cmap=cm.jet,colors=None)

    # set size of plot to match aspect ratio of map.
    l,b,w,h = ax.get_position()
    b = 0.5 - 0.5*w*m.aspect; h = w*m.aspect
    ax.set_position([l,b,w,h])
    
    # draw map.
    m.drawcoastlines()
	
    # draw parallels
    delat = 30.
    delon = 90.
    circles = arange(10.,90.+delat,delat).tolist()
    m.drawparallels(circles,labels=[0,0,1,1])
Beispiel #12
0
# Example to show how to make multi-panel plots.

# 2-panel plot, oriented vertically, colorbar on bottom.

rcParams['figure.subplot.hspace'] = 0.4 # more height between subplots
rcParams['figure.subplot.wspace'] = 0.5 # more width between subplots

# create new figure
fig=P.figure()
# panel 1
mnh = Basemap(lon_0=-105,boundinglat=20.,
             resolution='c',area_thresh=10000.,projection='nplaea')
xnh,ynh = mnh(lons,lats)
ax = fig.add_subplot(211)
CS = mnh.contour(xnh,ynh,hgt,15,linewidths=0.5,colors='k')
CS = mnh.contourf(xnh,ynh,hgt,15,cmap=P.cm.Spectral)
# colorbar on bottom.
l,b,w,h = ax.get_position()
cax = P.axes([l, b-0.05, w, 0.025]) # setup colorbar axes
P.colorbar(cax=cax, orientation='horizontal',ticks=CS.levels[0::4]) # draw colorbar
P.axes(ax)  # make the original axes current again
mnh.drawcoastlines(linewidth=0.5)
delat = 30.
circles = P.arange(0.,90.,delat).tolist()+\
          P.arange(-delat,-90,-delat).tolist()
mnh.drawparallels(circles,labels=[1,0,0,0])
delon = 45.
meridians = P.arange(0,360,delon)
mnh.drawmeridians(meridians,labels=[1,0,0,1])
P.title('NH 500 hPa Height (cm.Spectral)')
Beispiel #13
0
#plots = ['contour','imshow']

for np, plot in enumerate(plots):

    fig.add_subplot(1, 2, np + 1)
    ax = gca()

    # plot data.
    print plot + ' plot ...'
    if plot == 'pcolor':
        m.pcolor(x, y, hgt, shading='flat')
    elif plot == 'imshow':
        im = m.imshow(hgt)
    elif plot == 'contour':
        levels, colls = m.contour(x, y, hgt, 15, linewidths=0.5, colors='k')
        levels, colls = m.contourf(x, y, hgt, 15, cmap=cm.jet, colors=None)

    # set size of plot to match aspect ratio of map.
    l, b, w, h = ax.get_position()
    b = 0.5 - 0.5 * w * m.aspect
    h = w * m.aspect
    ax.set_position([l, b, w, h])

    # draw map.
    m.drawcoastlines()

    # draw parallels
    delat = 30.
    delon = 90.
    circles = arange(10., 90. + delat, delat).tolist()
    m.drawparallels(circles, labels=[0, 0, 1, 1])
Beispiel #14
0
# Example to show how to make multi-panel plots.

# 2-panel plot, oriented vertically, colorbar on bottom.

rcParams["figure.subplot.hspace"] = 0.4  # more height between subplots
rcParams["figure.subplot.wspace"] = 0.5  # more width between subplots

# create new figure
fig = P.figure()
# panel 1
mnh = Basemap(lon_0=-105, boundinglat=20.0, resolution="c", area_thresh=10000.0, projection="nplaea")
xnh, ynh = mnh(lons, lats)
ax = fig.add_subplot(211)
CS = mnh.contour(xnh, ynh, hgt, 15, linewidths=0.5, colors="k")
CS = mnh.contourf(xnh, ynh, hgt, 15, cmap=P.cm.Spectral)
# colorbar on bottom.
l, b, w, h = ax.get_position()
cax = P.axes([l, b - 0.05, w, 0.025])  # setup colorbar axes
P.colorbar(cax=cax, orientation="horizontal", ticks=CS.levels[0::4])  # draw colorbar
P.axes(ax)  # make the original axes current again
mnh.drawcoastlines(linewidth=0.5)
delat = 30.0
circles = P.arange(0.0, 90.0, delat).tolist() + P.arange(-delat, -90, -delat).tolist()
mnh.drawparallels(circles, labels=[1, 0, 0, 0])
delon = 45.0
meridians = P.arange(0, 360, delon)
mnh.drawmeridians(meridians, labels=[1, 0, 0, 1])
P.title("NH 500 hPa Height (cm.Spectral)")

# panel 2
Beispiel #15
0
    def display(self, dirc, **keywords):
        """ display  the data
        keywords: dict which can include the following keywords  minv=0.0, maxv=0.0, dv=0.0,
        show_map=0, map_proj='cyl', show_lat=0, show_lon=0, lat_0=0.0, lon_0=0.0,
        minlat=-90.0, maxlat=90.0, minlon=0.0, maxlon=360.0, use_log=0, level=level
        """

        rlat = self.grid.get_lat()
        rlon = self.grid.get_lon()

        levels = self.grid.get_z()

        minv = 0.0
        if ('minv' in keywords):
            minv = keywords['minv']

        maxv = 0.0

        if ('maxv' in keywords):
            maxv = keywords['maxv']

        dv = 0.0
        if ('dv' in keywords):
            dv = keywords['dv']

        show_map = 0

        if ('dv' in keywords):
            dv = keywords['dv']

        factor = 1.0
        if ('factor' in keywords):
            factor = keywords['factor']

        if (maxv > minv):
            rlvl = arange(minv, maxv + dv, dv)
            rlvl[0] = -999.0
            rlvl[size(rlvl) - 1] = 999.

        show_map = 0
        if ('show_map' in keywords):
            show_map = keywords['show_map']

        stitle = ""
        if ('name' in self.attr):
            add_str = self.attr['name']
        else:
            add_str = self.category
        add_str = add_str.strip()
        stitle = stitle + ' ' + add_str

        if ('traunit' in self.attr):
            add_str = self.attr['traunit']
        else:

            add_str = self.unit
        add_str = self.unit
        add_str = add_str.strip()
        cbar_vert = 1
        if ('cbar_vert' in keywords):
            cbar_vert = keyowrds['cbar_vert']

        if (cbar_vert == 1):
            orientation = 'vertical'
        else:
            orientation = 'horizontal'

        stitle = stitle + ' (' + add_str + ')'
        if ('tau0' in self.attr):
            tau0 = self.attr['tau0']
            tau0 = 3600. * tau0  # convert to seconds
            utc = tm.tai85_to_utc(tau0)
            stitle = stitle + ' ' + utc

        if (show_map == 1):
            level = 0
            if ('level' in keywords):
                level = keywords['level']

            show_lat = 1
            if ('show_lat' in keywords):
                show_lat = keywords['show_lat']

            show_lon = 1
            if ('show_lon' in keywords):
                show_lon = keywords['show_lon']

            vals = self.data[:, :, level]
            vals = array(vals)
            vals = factor * vals

            map_proj = 'cyl'
            if ('map_proj' in keywords):
                map_proj = keywords['map_proj']
            lat_0 = 0.0
            if ('lat_0' in keywords):
                lat_0 = keywords['lat_0']

            minlat = -90.0
            if ('minlat' in keywords):
                minlat = keywords['minlat']

            maxlat = 90.0

            if ('maxlat' in keywords):
                maxlat = keywords['maxlat']

            if (self.grid.centre180 == 0):
                minlon = 0.0
                maxlon = 360.0
                lon_0 = 180
            else:
                minlon = -180
                maxlon = 180.0
                lon_0 = 0

            if ('minlon' in keywords):
                minlon = keywords['minlon']

            if ('maxlon' in keywords):
                maxlon = keywords['maxlon']

            if ('lon_0' in keywords):
                lon_0 = keywords['lon_0']

            boundinglat = 45
            if ('boundinglat' in keywords):
                boundinglat = keywords['boundinglat']
            if (map_proj == 'npstere' or map_proj == 'spstere'):
                m = Basemap(projection=map_proj,
                            lon_0=lon_0,
                            boundinglat=boundinglat)
            elif (map_proj == 'ortho'):
                m = Basemap(projection=map_proj, lon_0=lon_0, lat_0=lat_0)
            else:
                m = Basemap(llcrnrlon=minlon,
                            llcrnrlat=minlat,
                            urcrnrlon=maxlon,
                            urcrnrlat=maxlat,
                            projection=map_proj,
                            lon_0=lon_0,
                            lat_0=lat_0)

            if (rlon[-1] < rlon[0] + 360.0):
                rlon = resize(rlon, self.grid.ix + 1)
                rlon[-1] = rlon[0] + 360.0
                vals = squeeze(vals)
                vals = resize(vals, [self.grid.ix + 1, self.grid.jx])

            x, y = m(*meshgrid(rlon, rlat))

            if (maxv > minv):
                cs0 = m.contourf(x, y, transpose(vals), rlvl)
            else:
                cs0 = m.contourf(x, y, transpose(vals))

            m.drawcoastlines()
            m.drawcountries()
            m.drawmapboundary()
            if (show_lat == 1):
                print(minlat, maxlat)
                print(minlon, maxlon)
                m.drawparallels(arange(minlat, maxlat + 30.0, 30.),
                                labels=[1, 0, 0, 0])
            if (show_lon == 1):
                m.drawmeridians(arange(minlon, maxlon + 60, 60.),
                                labels=[0, 0, 0, 1])
            title(stitle)
            colorbar(orientation=orientation)
        elif (dirc == 0):
            level = 0
            if ('level' in keywords):
                lvl = keywords['level']

            vals = self.data[:, :, level]
            vals = factor * vals
            print(shape(vals), shape(rlon), shape(rlat))

            if (maxv > minv):
                contourf(rlon, rlat, transpose(vals), rlvl)
            else:
                contourf(rlon, rlat, transpose(vals))
            # restart_new
            title(stitle)
            xlabel('Lon')
            ylabel('Lat')

            colorbar()
        elif (dirc == 1):
            vals = average(self.data, axis=0)
            use_log = 0
            if ('use_log' in keywords):
                use_log = keywords['use_log']
            ax = subplot(2, 1, 1)
            if (use_log == 1):
                ax.set_yscale('log')
            levels = self.get_level()
            if ('level' in keywords):
                levels = keywords['levels']

            if (maxv > minv):
                contourf(rlon, rlat, transpose(vals), rlvl)
            else:
                contourf(rlat, levels, vals)

            xlabel('Lat')
            ylabel('Level')

            title(stitle)
            colorbar()

        show()
        return 0
Beispiel #16
0
hgt = load('500hgtdata.gz')
lons = load('500hgtlons.gz')
lats = load('500hgtlats.gz')
# shift data so lons go from -180 to 180 instead of 0 to 360.
hgt,lons = shiftgrid(180.,hgt,lons,start=False)
lons, lats = meshgrid(lons, lats)

# create new figure
fig=figure()
# setup of sinusoidal basemap
m = Basemap(resolution='c',projection='sinu',lon_0=0)
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# make a filled contour plot.
x, y = m(lons, lats)
CS = m.contour(x,y,hgt,15,linewidths=0.5,colors='k')
CS = m.contourf(x,y,hgt,15,cmap=cm.jet)
l,b,w,h=ax.get_position()
cax = axes([l+w+0.075, b, 0.05, h]) # setup colorbar axes
colorbar(drawedges=True, cax=cax) # draw colorbar
axes(ax)  # make the original axes current again
# draw coastlines and political boundaries.
m.drawcoastlines()
m.drawmapboundary()
m.fillcontinents()
# draw parallels and meridians.
parallels = arange(-60.,90,30.)
m.drawparallels(parallels,labels=[1,0,0,0])
meridians = arange(-360.,360.,30.)
m.drawmeridians(meridians)
title('Sinusoidal Filled Contour Demo')
print 'plotting with sinusoidal basemap ...'
Beispiel #17
0
    area_thresh=5000.0,
    projection="lcc",
    lat_1=standardpar,
    lon_0=centerlon,
)
x, y = m(lons, lats)
# setup figure size so each panel will have same aspect ratio as map.
xsize = rcParams["figure.figsize"][0]
ysize = (3.0 / 2.0) * m.aspect * xsize
fig = figure(figsize=(xsize, ysize))
yoffset = (m.urcrnry - m.llcrnry) / 30.0
for npanel, fcsthr in enumerate(arange(0, 72, 12)):
    nt = fcsthrs.index(fcsthr)
    ax = fig.add_subplot(320 + npanel + 1)
    levels, colls = m.contour(x, y, t2m[nt, :, :], clevs, colors="k")
    levels, colls = m.contourf(x, y, t2m[nt, :, :], clevs, cmap=cm.jet, colors=None)
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.drawparallels(arange(25, 75, 20), labels=[1, 0, 0, 0], fontsize=8, fontstyle="oblique")
    m.drawmeridians(arange(-140, 0, 20), labels=[0, 0, 0, 1], fontsize=8, yoffset=yoffset, fontstyle="oblique")
    # panel title
    title(repr(fcsthr) + "-h forecast valid " + verifdates[nt], fontsize=12)
clim(clevs[1], clevs[-2])
# figure title
figtext(
    0.5,
    0.95,
    u"2-m temp (\N{DEGREE SIGN}K) forecasts from %s" % verifdates[0],
    horizontalalignment="center",
    fontsize=14,
Beispiel #18
0
# setup of basemap ('ortho' = orthographic projection)
m = Basemap(projection='ortho',
            resolution='c',
            area_thresh=10000.,
            lat_0=30,
            lon_0=-60)
xsize = rcParams['figure.figsize'][0]
fig = figure(figsize=(xsize, m.aspect * xsize))
ax = fig.add_axes([0.1, 0.1, 0.7, 0.7], frameon=False)
# pcolor plot (slow)
#x,y = m(*meshgrid(lons,lats))
#p = m.pcolor(x,y,topodatin,shading='flat')
# filled contours (faster)
x, y = m(*meshgrid(lonsin, latsin))
levels, colls = m.contourf(x, y, topodatin, 20, cmap=cm.jet, colors=None)
cax = axes([0.875, 0.1, 0.05, 0.7])  # setup colorbar axes
colorbar(tickfmt='%d', cax=cax)  # draw colorbar
axes(ax)  # make the original axes current again
# draw coastlines and political boundaries.
m.drawcoastlines()
# draw parallels and meridians (labelling is
# not implemented for orthographic).
parallels = arange(-80., 90, 20.)
m.drawparallels(parallels)
meridians = arange(0., 360., 20.)
m.drawmeridians(meridians)
# draw boundary around map region.
m.drawmapboundary()
title('Orthographic')
print 'plotting Orthographic example, close plot window to proceed ...'
Beispiel #19
0
def plot_ncdf_output(id, datafn, **kwds):
    """Plot model field id from the data in netCDF file datafn.

    Positional Input Parameter:
    * id:  Name of the id of the field to plot.  String.

    * datafn:  Filename containing the output data to plot.  String.

    Input keyword parameter descriptions are found in the docstring
    for Qtcm methods ploti, plotm, and other methods that call this
    private method.  In general, those methods take the keyword
    parameters they receive and pass it along unchanged as keyword
    parameters to this function.  In that sense, this function is
    seldom used as a stand-alone function, but rather is usually
    used coupled with a Qtcm instance.

    The data fields read in from the netCDF output file are dimensioned
    (time, lat, lon).  This is different than how the data is stored
    in the compiled QTCM model fields (lon, lat, time), and at the
    Python level (lon, lat).  The reason this is the case is that
    f2py automatically makes the arrays passed between the Python
    and Fortran levels match.

    For a lat vs. lon plot, the contour plot is superimposed onto
    a cylindrical projection map of the Earth with continents drawn
    and labeled meridians and parallels.  The title also includes
    the model time, and x- and y-axis labels are not drawn.

    All numerical data used for plotting come from the netCDF output
    file for consistency (e.g., the dimensions of u1).  Currently
    this method only works for 3-D data arrays (two in space, one
    in time).
    """
    #- Accomodate other ids.  The id that this routine will use
    #  (i.e., iduse corresponds to the name in the netCDF output file)
    #  is called iduse.  Set this to id, except for the case where
    #  some aliases of ids are entered in which iduse is the alias:

    if id == 'Qc': iduse = 'Prec'
    elif id == 'FLWut': iduse = 'OLR'
    elif id == 'STYPE': iduse = 'stype'
    else: iduse = id

    #- Set defined keyword defaults.  All are set to None except for
    #  nlatlon which gets an integer:

    plotkwds_ids = [
        'lat', 'lon', 'time', 'fn', 'levels', 'title', 'xlabel', 'ylabel',
        'filled', 'nlatlon', 'tmppreview'
    ]

    plotkwds = {}
    for ikey in plotkwds_ids:
        if kwds.has_key(ikey):
            plotkwds[ikey] = copy.copy(kwds[ikey])
        else:
            plotkwds[ikey] = None

    if not kwds.has_key('nlatlon'):
        plotkwds['nlatlon'] = 8

    #- Get data and dimensions of iduse to plot:

    fileobj = S.NetCDFFile(datafn, mode='r')
    data = N.array(fileobj.variables[iduse].getValue())
    data_name = fileobj.variables[iduse].long_name
    data_units = fileobj.variables[iduse].units

    dim = {}
    dimname = {}
    dimunits = {}

    dim['lat'] = N.array(fileobj.variables['lat'].getValue())
    dimname['lat'] = fileobj.variables['lat'].long_name
    dimunits['lat'] = fileobj.variables['lat'].units

    dim['lon'] = N.array(fileobj.variables['lon'].getValue())
    dimname['lon'] = fileobj.variables['lon'].long_name
    dimunits['lon'] = fileobj.variables['lon'].units

    dim['time'] = N.array(fileobj.variables['time'].getValue())
    dimname['time'] = fileobj.variables['time'].long_name
    dimunits['time'] = fileobj.variables['time'].units

    fileobj.close()

    #- Alter data long name to remove any units.  The definition
    #  of units as the substring within the [] is the same as used in
    #  defVar in output.F90 of the compiled QTCM model.  Remove
    #  underscores and extra whitespace in data_name and data_units,
    #  replacing with a single whitespace character between words:

    idx1 = data_name.find('[')
    idx2 = data_name.find(']')
    if idx1 != -1 and idx2 != -1:
        data_name = data_name[:idx1] + data_name[idx2 + 1:]
    data_name = data_name.strip()

    data_name = ' '.join(data_name.replace('_', ' ').split())
    data_units = ' '.join(data_units.replace('_', ' ').split())

    #- Alter dimension long name to remove any units.  The definition
    #  of units as the substring within the [] is the same as used in
    #  defVar in output.F90 of the compiled QTCM model.  Remove
    #  underscores and extra whitespace in name and units, replacing
    #  with a single whitespace character between words, and
    #  capitalizing like a title:

    for idimkey in dim.keys():
        idimname = dimname[idimkey]
        idx1 = idimname.find('[')
        idx2 = idimname.find(']')
        if idx1 != -1 and idx2 != -1:
            idimname = idimname[:idx1] + idimname[idx2 + 1:]
        dimname[idimkey] = idimname.strip()

        dimname[idimkey]  = \
            ' '.join(dimname[idimkey].replace('_',' ').split()).title()
        dimunits[idimkey] = \
            ' '.join(dimunits[idimkey].replace('_',' ').split()).title()

    #- Some data checks:

    if N.rank(data) != 3:
        raise ValueError, '_plot: can only plot lat, lon, time fields'
    if not N.allclose(dim['time'], N.sort(dim['time'])):
        raise ValueError, '_plot: time not monotonically ascending'
    if not N.allclose(dim['lat'], N.sort(dim['lat'])):
        raise ValueError, '_plot: lat not monotonically ascending'
    if not N.allclose(dim['lon'], N.sort(dim['lon'])):
        raise ValueError, '_plot: lon not monotonically ascending'
    if N.shape(data)[0] != N.size(dim['time']):
        raise ValueError, '_plot: data time dim mismatch'
    if N.shape(data)[1] != N.size(dim['lat']):
        raise ValueError, '_plot: data lat dim mismatch'
    if N.shape(data)[2] != N.size(dim['lon']):
        raise ValueError, '_plot: data lon dim mismatch'

    #- Choose and describe ranges for lat, lon, and time.  The
    #  section cycles through the dictionary of dimensions.  idim is
    #  the 1-D array of the values of that dimension.  rngs is a
    #  dictionary where each entry corresponds to a dimension, and the
    #  value of the entry is the values of that dimension that are to
    #  be plotted.  rngs_idxs are the indices in the original
    #  dimensions array corresponding to the values in rngs.
    #  keys_rngs_sizes_gt_1 is a list of the keys of ranges that have
    #  sizes greater than 1:

    rngs = {}
    rngs_idxs = {}
    keys_rngs_sizes_gt_1 = []
    for idimkey in dim.keys():
        idim = dim[idimkey]

        if plotkwds[idimkey] == None:
            dim_mask = N.ones(N.size(idim), dtype=int)

        elif N.isscalar(plotkwds[idimkey]):
            dim_mask = where_close(idim, plotkwds[idimkey])
            if N.sum(dim_mask) != 1:
                raise ValueError, 'no point chosen'

        elif (not N.isscalar(plotkwds[idimkey])) and \
             N.size(plotkwds[idimkey]) == 1:
            dim_mask = where_close(idim, plotkwds[idimkey][0])
            if N.sum(dim_mask) != 1:
                raise ValueError, 'no point chosen'

        elif N.size(plotkwds[idimkey]) == 2:
            dim_mask = N.logical_and(idim >= plotkwds[idimkey][0],
                                     idim <= plotkwds[idimkey][-1])

        else:
            raise ValueError, 'bad dimension range keyword entry'

        rngs[idimkey] = N.compress(dim_mask, idim)
        rngs_idxs[idimkey] = N.compress(dim_mask, N.arange(N.size(idim)))
        if N.size(rngs[idimkey]) > 1:
            keys_rngs_sizes_gt_1.append(idimkey)

    #- Set plot types (line or contour):

    if len(keys_rngs_sizes_gt_1) == 0:
        raise ValueError, 'cannot plot without any fixed dimension'
    elif len(keys_rngs_sizes_gt_1) == 1:
        plottype = 'line'
    elif len(keys_rngs_sizes_gt_1) == 2:
        plottype = 'contour'
    else:
        raise ValueError, 'cannot plot with > 2 varying dimensions'

    #- Set plot axis fields and axis names, depending on what sort
    #  of dimensions will be plotted.  If lon is to be plotted, it is
    #  always the x-axis.  If lat is to be plotted, it is always the
    #  y-axis.  In this section and later on in a few places, I
    #  rely on the count method for a list as a Boolean test:  If it
    #  returns 0, consider that False; > 0 is True.  The text for the
    #  title and axis labels to be passed to the xlabel, etc. methods,
    #  are called titlename, xname, and yname:

    if plottype == 'line':  #+ Choose x-axis vector and
        x = rngs[keys_rngs_sizes_gt_1[0]]  #  x/y names for line plot
        xname = dimname[keys_rngs_sizes_gt_1[0]] + ' [' \
              + dimunits[keys_rngs_sizes_gt_1[0]] + ']'
        yname = data_name + ' [' + data_units + ']'

    elif plottype == 'contour':  #+ Choose axis vectors and
        if keys_rngs_sizes_gt_1.count('lon'):  #  names for contour plot
            x = rngs['lon']
            xname = dimname['lon'] + ' [' + dimunits['lon'] + ']'
        if keys_rngs_sizes_gt_1.count('lat'):
            y = rngs['lat']
            yname = dimname['lat'] + ' [' + dimunits['lat'] + ']'
        if keys_rngs_sizes_gt_1.count('time'):
            if keys_rngs_sizes_gt_1.count('lon'):
                y = rngs['time']
                yname = dimname['time'] + ' [' + dimunits['time'] + ']'
            elif keys_rngs_sizes_gt_1.count('lat'):
                x = rngs['time']
                xname = dimname['time'] + ' [' + dimunits['time'] + ']'
            else:
                raise ValueError, 'bad treatment of time'

    else:
        raise ValueError, 'unrecognized plottype'

    #- Override xname, yname, and titlename with keywords, if they
    #  are not None.  titlename receives data_name and data_units
    #  by default:

    if plotkwds['xlabel'] != None:
        xname = plotkwds['xlabel']
    if plotkwds['ylabel'] != None:
        yname = plotkwds['ylabel']

    if plotkwds['title'] != None:
        titlename = plotkwds['title']
    else:
        titlename = data_name + ' [' + data_units + ']'

    #- Pick data to be plotted and plot:

    pylab.clf()  #+ Clear any previous figures
    pylab.figure(1)  #+ Open a pylab figure

    if plottype == 'line':  #+ Select data for a line plot
        y = data[rngs_idxs['time'],  #  and plot
                 rngs_idxs['lat'], rngs_idxs['lon']]
        pylab.plot(x, y)

    elif plottype == 'contour':  #+ Select data for a contour
        ritim = rngs_idxs['time']  #  plot and plot
        rilat = rngs_idxs['lat']
        rilon = rngs_idxs['lon']

        #* Extract subarrays depending on which two dimensions are
        #  chosen:

        if N.size(rngs_idxs['time']) == 1:
            zgrid = num.MLab.squeeze(data[ritim[0], rilat[0]:rilat[-1] + 1,
                                          rilon[0]:rilon[-1] + 1])
        elif N.size(rngs_idxs['lat']) == 1:
            zgrid = num.MLab.squeeze(data[ritim[0]:ritim[-1] + 1, rilat[0],
                                          rilon[0]:rilon[-1] + 1])
        elif N.size(rngs_idxs['lon']) == 1:
            zgrid = num.MLab.squeeze(data[ritim[0]:ritim[-1] + 1,
                                          rilat[0]:rilat[-1] + 1, rilon[0]])
        else:
            raise ValueError, 'unrecognized configuration'

        #* Change zgrid for special case of a lat. vs. time contour
        #  plot.  Calculate xgrid and ygrid:

        if keys_rngs_sizes_gt_1.count('time') and \
           keys_rngs_sizes_gt_1.count('lat'):
            zgrid = N.transpose(zgrid)

        xgrid, ygrid = pylab.meshgrid(x, y)

        #* Set contour levels:

        if plotkwds['levels'] == None:
            levels = nice_levels(zgrid)
        else:
            levels = plotkwds['levels']

        #- Plot (creating continents first if is a lat vs. lon plot)
        #  and write contour levels/color bar as appropriate:

        if keys_rngs_sizes_gt_1.count('lon') and \
           keys_rngs_sizes_gt_1.count('lat'):
            mapplot = Basemap(projection='cyl',
                              resolution='l',
                              llcrnrlon=N.min(xgrid),
                              llcrnrlat=N.min(ygrid),
                              urcrnrlon=N.max(xgrid),
                              urcrnrlat=N.max(ygrid))
            mapplot.drawcoastlines()
            mapplot.drawmeridians(nice_levels(rngs['lon'],
                                              approx_nlev=plotkwds['nlatlon']),
                                  labels=[1, 0, 0, 1])
            mapplot.drawparallels(nice_levels(rngs['lat'],
                                              approx_nlev=plotkwds['nlatlon']),
                                  labels=[1, 0, 0, 1])
            if plotkwds['filled']:
                plot = mapplot.contourf(xgrid, ygrid, zgrid, levels)
                pylab.colorbar(plot, orientation='horizontal', format='%g')
            else:
                plot = mapplot.contour(xgrid, ygrid, zgrid, levels)
                pylab.clabel(plot, inline=1, fontsize=10, fmt='%g')
        else:
            if plotkwds['filled']:
                plot = pylab.contourf(xgrid, ygrid, zgrid, levels)
                pylab.colorbar(plot, orientation='horizontal', format='%g')
            else:
                plot = pylab.contour(xgrid, ygrid, zgrid, levels)
                pylab.clabel(plot, inline=1, fontsize=10, fmt='%g')

    else:
        raise ValueError, 'unrecognized plottype'

    #- Add titling.  Lat vs. lon plots do not have axis labels because
    #  the map labels already make it clear, and for those plots the
    #  title also includes the time value:

    if keys_rngs_sizes_gt_1.count('lon') and \
       keys_rngs_sizes_gt_1.count('lat'):
        titlename = titlename + ' at ' \
                  + dimname['time'] + ' ' \
                  + str(rngs['time'][0]) + ' ' \
                  + dimunits['time']
        titlename = mpl_latex_script1(titlename)
        pylab.title(titlename)
    else:
        titlename = mpl_latex_script1(titlename)
        xname = mpl_latex_script1(xname)
        yname = mpl_latex_script1(yname)
        pylab.xlabel(xname)
        pylab.ylabel(yname)
        pylab.title(titlename)

    #- Output plot to PNG file or screen.  The show command seems to
    #  have a problem on my Mac OS X, so save to a temporary file
    #  and use preview to view for fn == None and tmppreview set to
    #  True.  Note that the temporary file is not deleted by this
    #  method:

    if plotkwds['fn'] == None:  #+ Screen display
        if plotkwds['tmppreview'] and sys.platform == 'darwin':
            outputfn = tempfile.mkstemp('.png', 'qtcm_')
            pylab.savefig(outputfn[-1])
            os.system('open -a /Applications/Preview.app ' + outputfn[-1])
        else:
            pylab.show()

    elif type(plotkwds['fn']) == type('a'):  #+ Write to file
        pylab.savefig(plotkwds['fn'])
        pylab.close(1)

    else:
        raise ValueError, 'cannot write to this type of file'
Beispiel #20
0
    figure(figsize=(8, 8))
    subplot(ncol, nrow, nslice)
    for i in xrange(nslice):
        lon = composites.getLongitude()
        lat = composites.getLatitude()
        xx, yy = meshgrid(lon, lat)
        m = Basemap(resolution='l',
                    lat_0=N.average(lat),
                    lon_0=N.average(lon),
                    llcrnrlon=min(lon),
                    llcrnrlat=min(lat),
                    urcrnrlon=max(lon),
                    urcrnrlat=max(lat))
        levels = vcs.mkscale(genutil.minmax(composites))
        m.contourf(lon, lat, composites[i], levels=levels, cmap=bwr)
        clabel(m.contour(lon, lat, composites[i], levels=levels))
        title("Phase %i/%i" (i + 1, 6))
        m.drawcoastlines()
        m.drawcountries()
        m.fillcontinents(color='coral')
        m.drawparallels(vcs.mkscale(genutil.minmax(lat)), labels=[1, 0, 0, 0])
        m.drawmeridians(vcs.mkscale(genutil.minmax(lon)), labels=[0, 0, 0, 1])
    figtext(
        .5, 1.,
        "\n%s [%s]" % ("El Nino phase composites\nSea surface temperature",
                       composites.units))
    savefig(sys.argv[0].replace(".py", ".png"))
    show()

# Fall back to vcs because we have it!
Beispiel #21
0
tlon = tlon - 360.

pl.figure(figsize=(8.5, 11))
pl.subplot(2, 1, 1)
# subplot 1 just shows POP grid cells.
map = Basemap(projection='merc', lat_ts=20, llcrnrlon=-180, \
      urcrnrlon=180, llcrnrlat=-84, urcrnrlat=84, resolution='c')

map.drawcoastlines()
map.fillcontinents(color='white')

x, y = map(tlon, tlat)
im = map.pcolor(x,y,MA.masked_array(N.zeros(temp.shape,'f'), temp.mask),\
                shading='faceted',cmap=pl.cm.cool,vmin=0,vmax=0)
# disclaimer:  these are not really the grid cells because of the
# way pcolor interprets the x and y args.
pl.title('(A) CCSM POP Grid Cells')

# subplot 2 is a contour plot of surface temperature from the
# CCSM ocean model.
pl.subplot(2, 1, 2)
map.drawcoastlines()
map.fillcontinents(color='white')

CS1 = map.contourf(x, y, temp, 15)
CS2 = map.contour(x, y, temp, 15, colors='black', linewidths=0.5)
pl.title('(B) Surface Temp contours on POP Grid')

pl.show()
#pl.savefig('ccsm_popgrid.ps')
Beispiel #22
0
pl.figure(figsize=(8.5,11))
pl.subplot(2,1,1)
# subplot 1 just shows POP grid cells.
map = Basemap(projection='merc', lat_ts=20, llcrnrlon=-180, \
      urcrnrlon=180, llcrnrlat=-84, urcrnrlat=84, resolution='c')

map.drawcoastlines()
map.fillcontinents(color='white')

x, y = map(tlon,tlat)
im = map.pcolor(x,y,MA.masked_array(N.zeros(temp.shape,'f'), temp.mask),\
                shading='faceted',cmap=pl.cm.cool,vmin=0,vmax=0)
# disclaimer:  these are not really the grid cells because of the
# way pcolor interprets the x and y args.
pl.title('(A) CCSM POP Grid Cells')

# subplot 2 is a contour plot of surface temperature from the
# CCSM ocean model.
pl.subplot(2,1,2)
map.drawcoastlines()
map.fillcontinents(color='white')

CS1 = map.contourf(x,y,temp,15)
CS2 = map.contour(x,y,temp,15,colors='black',linewidths=0.5)
pl.title('(B) Surface Temp contours on POP Grid')

pl.show()
#pl.savefig('ccsm_popgrid.ps')

Beispiel #23
0
map = Basemap(projection='cyl',
              resolution='l',
              llcrnrlon=0,
              urcrnrlon=360,
              llcrnrlat=-76.875,
              urcrnrlat=76.875,
              lon_0=180,
              lat_0=0)
map.drawmeridians(p.arange(0, 361, 45), labels=[0, 0, 0, 1])
map.drawparallels(p.arange(-90, 90, 30), labels=[1, 0, 0, 1])
map.drawcoastlines()

#--- Write out contour map and view using preview:

x, y = p.meshgrid(lon, lat)
CS = map.contourf(x, y, u1, cmap=p.cm.gray)
p.text(0.5,
       -0.15,
       'Longitude [deg]',
       horizontalalignment='center',
       verticalalignment='center',
       transform=p.gca().transAxes)
p.text(-0.11,
       0.5,
       'Latitude [deg]',
       rotation='vertical',
       horizontalalignment='center',
       verticalalignment='center',
       transform=p.gca().transAxes)
p.title('QTCM u1')
cbar = p.colorbar(CS, orientation='horizontal', shrink=0.6)
Beispiel #24
0
# read in topo data from pickle (on a regular lat/lon grid)
topodict = cPickle.load(open('etopo20.pickle','rb'))
etopo = topodict['data']; lons = topodict['lons']; lats = topodict['lats']
# create figure.
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_axes([0.125,0.175,0.75,0.75],frameon=False)
# create Basemap instance for Robinson projection.
# set 'ax' keyword so pylab won't be imported.
m = Basemap(projection='robin',lon_0=0.5*(lons[0]+lons[-1]),ax=ax)
# reset figure size to have same aspect ratio as map.
# fig will be 8 inches wide.
fig.set_figsize_inches((8,m.aspect*8.))
# make filled contour plot.
x, y = m(*meshgrid(lons, lats))
levels, colls = m.contourf(x,y,etopo,30,cmap=cm.jet,colors=None)
# draw coastlines.
m.drawcoastlines()
# draw a line around the map region.
m.drawmapboundary()
# draw parallels and meridians.
m.drawparallels(nx.arange(-60.,90.,30.),labels=[1,0,0,0],fontsize=10)
m.drawmeridians(nx.arange(0.,420.,60.),labels=[0,0,0,1],fontsize=10)
# add a title.
ax.set_title('Robinson Projection')
# add a colorbar.
cax = fig.add_axes([0.25, 0.05, 0.5, 0.05],frameon=False)
fig.colorbar(colls.mappable, cax=cax, tickfmt='%d', orientation='horizontal') 
# save image (width 800 pixels with dpi=100 and fig width 8 inches).
canvas.print_figure('simpletest',dpi=100)
# done.
Beispiel #25
0
lons[0:len(lonsin)] = lonsin-0.5*delon
lons[-1] = lonsin[-1]+0.5*delon
lats[0:len(latsin)] = latsin-0.5*delat
lats[-1] = latsin[-1]+0.5*delat

# setup of basemap ('ortho' = orthographic projection)
m = Basemap(projection='ortho',
            resolution='c',area_thresh=10000.,lat_0=30,lon_0=-60)
fig=m.createfigure()
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# pcolor plot (slow)
#x,y = m(*meshgrid(lons,lats))
#p = m.pcolor(x,y,topodatin,shading='flat')
# filled contours (faster)
x,y = m(*meshgrid(lonsin,latsin))
cs = m.contourf(x,y,topodatin,20,cmap=cm.jet)
cax = axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes
colorbar(tickfmt='%d', cax=cax) # draw colorbar
axes(ax)  # make the original axes current again
# draw coastlines and political boundaries.
m.drawcoastlines()
# draw parallels and meridians (labelling is 
# not implemented for orthographic).
parallels = arange(-80.,90,20.)
m.drawparallels(parallels)
meridians = arange(0.,360.,20.)
m.drawmeridians(meridians)
# draw boundary around map region.
m.drawmapboundary()
title('Orthographic')
print 'plotting Orthographic example, close plot window to proceed ...'
Beispiel #26
0
# plot vectors in geographical (lat/lon) coordinates.

# north polar projection.
m = Basemap(llcrnrlon=-180.,llcrnrlat=10.,urcrnrlon=0.,urcrnrlat=10.,\
            resolution='c',area_thresh=10000.,projection='stere',\
            lat_0=90.,lon_0=-135.,lat_ts=90.)
# setup figure with same aspect ratio as map.
xsize = rcParams['figure.figsize'][0]
fig=figure(figsize=(xsize,m.aspect*xsize))
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# rotate wind vectors to map projection coordinates.
# (also compute native map projections coordinates of lat/lon grid)
# only do Northern Hemisphere.
urot,vrot,x,y = m.rotate_vector(u[36:,:],v[36:,:],lons[36:,:],lats[36:,:],returnxy=True)
# plot filled contours over map.
levels, colls = m.contourf(x,y,p[36:,:],15,cmap=cm.jet,colors=None)
# plot wind vectors over map.
m.quiver(x,y,urot,vrot)
cax = axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes.
colorbar(tickfmt='%d', cax=cax) # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
m.drawcountries()
# draw parallels
delat = 20.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles,labels=[1,1,1,1])
# draw meridians
delon = 45.
meridians = arange(-180,180,delon)
Beispiel #27
0
                                        lats,
                                        nxv,
                                        nyv,
                                        returnxy=True)
pdat, xp, yp = m.transform_scalar(p, lons, lats, nxp, nyp, returnxy=True)

print min(ravel(udat)), max(ravel(udat))
print min(ravel(vdat)), max(ravel(vdat))
print min(ravel(pdat)), max(ravel(pdat))
spd = sqrt(udat**2 + vdat**2)
print max(ravel(spd))

xsize = rcParams['figure.figsize'][0]
fig = figure(figsize=(xsize, m.aspect * xsize))
ax = fig.add_axes([0.1, 0.1, 0.7, 0.7])
levels, colls = m.contourf(xp, yp, pdat, 15, cmap=cm.jet, colors=None)
m.quiver(xv, yv, udat, vdat)
cax = axes([0.875, 0.1, 0.05, 0.7])
colorbar(tickfmt='%d', cax=cax)  # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
m.drawcountries()
# draw parallels
delat = 20.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles, labels=[1, 1, 1, 1])
# draw meridians
delon = 45.
meridians = arange(-180, 180, delon)
m.drawmeridians(meridians, labels=[1, 1, 1, 1])
Beispiel #28
0
#--- Mapping information:

map = Basemap( projection='cyl', resolution='l'
             , llcrnrlon=0, urcrnrlon=360
             , llcrnrlat=-76.875, urcrnrlat=76.875
             , lon_0=180, lat_0=0
             )
map.drawmeridians(p.arange(0,361,45), labels=[0,0,0,1])
map.drawparallels(p.arange(-90,90,30), labels=[1,0,0,1])
map.drawcoastlines()


#--- Write out contour map and view using preview:

x, y = p.meshgrid(lon,lat)
CS = map.contourf(x, y, u1, cmap=p.cm.gray)
p.text( 0.5, -0.15, 'Longitude [deg]'
      , horizontalalignment='center'
      , verticalalignment='center'
      , transform = p.gca().transAxes )
p.text( -0.11, 0.5, 'Latitude [deg]'
      , rotation='vertical'
      , horizontalalignment='center'
      , verticalalignment='center'
      , transform = p.gca().transAxes )
p.title('QTCM u1')
cbar = p.colorbar(CS, orientation='horizontal', shrink=0.6)
cbar.ax.set_xlabel('See QTCM Documentation')
p.savefig('foo.png')
os.system('preview foo.png')
Beispiel #29
0
            lon_0=centerlon)
x, y = m(lons, lats)
# setup figure size so each panel will have same aspect ratio as map.
xsize = rcParams['figure.figsize'][0]
ysize = (3. / 2.) * m.aspect * xsize
fig = figure(figsize=(xsize, ysize))
yoffset = (m.urcrnry - m.llcrnry) / 30.
for npanel, fcsthr in enumerate(arange(0, 72, 12)):
    nt = fcsthrs.index(fcsthr)
    ax = fig.add_subplot(320 + npanel + 1)
    # make a pcolor plot.
    #p = m.pcolor(x,y,t2m[nt,:,:],shading='flat',cmap=cm.jet)
    # make a filled contour plot.
    levels, colls = m.contourf(x,
                               y,
                               t2m[nt, :, :],
                               20,
                               cmap=cm.jet,
                               colors=None)
    clim(t2min, t2max)  # fix color range to be the same for all panels
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.drawparallels(arange(25, 75, 20),
                    labels=[1, 0, 0, 0],
                    fontsize=8,
                    fontstyle='oblique')
    m.drawmeridians(arange(-140, 0, 20),
                    labels=[0, 0, 0, 1],
                    fontsize=8,
                    yoffset=yoffset,
                    fontstyle='oblique')
Beispiel #30
0
lons, lats = meshgrid(lons1, lats1)

# plot vectors in geographical (lat/lon) coordinates.

# north polar projection.
m = Basemap(lon_0=-135,boundinglat=25,
            resolution='c',area_thresh=10000.,projection='npstere')
# create a figure, add an axes.
fig=figure(figsize=(8,8))
ax = fig.add_axes([0.1,0.1,0.7,0.7])
# rotate wind vectors to map projection coordinates.
# (also compute native map projections coordinates of lat/lon grid)
# only do Northern Hemisphere.
urot,vrot,x,y = m.rotate_vector(u[36:,:],v[36:,:],lons[36:,:],lats[36:,:],returnxy=True)
# plot filled contours over map.
cs = m.contourf(x,y,p[36:,:],15,cmap=cm.jet)
# plot wind vectors over map.
Q = m.quiver(x,y,urot,vrot) #or specify, e.g., width=0.003, scale=400)
qk = quiverkey(Q, 0.95, 1.05, 25, '25 m/s', labelpos='W')
cax = axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes.
colorbar(cax=cax) # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
m.drawcountries()
# draw parallels
delat = 20.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles,labels=[1,1,1,1])
# draw meridians
delon = 45.
Beispiel #31
0
# read in data on lat/lon grid.
hgt = load('500hgtdata.gz')
lons = load('500hgtlons.gz')
lats = load('500hgtlats.gz')
# shift data so lons go from -180 to 180 instead of 0 to 360.
hgt, lons = shiftgrid(180., hgt, lons, start=False)
lons, lats = meshgrid(lons, lats)

# setup of sinusoidal basemap
m = Basemap(resolution='c', projection='sinu', lon_0=0)
fig = figure()
ax = fig.add_axes([0.1, 0.1, 0.7, 0.7])
# make a filled contour plot.
x, y = m(lons, lats)
CS = m.contour(x, y, hgt, 15, linewidths=0.5, colors='k')
CS = m.contourf(x, y, hgt, 15, cmap=cm.jet)
l, b, w, h = ax.get_position()
cax = axes([l + w + 0.075, b, 0.05, h])  # setup colorbar axes
colorbar(drawedges=True, cax=cax)  # draw colorbar
axes(ax)  # make the original axes current again
# draw coastlines and political boundaries.
m.drawcoastlines()
m.drawmapboundary()
m.fillcontinents()
# draw parallels and meridians.
parallels = arange(-60., 90, 30.)
m.drawparallels(parallels, labels=[1, 0, 0, 0])
meridians = arange(-360., 360., 30.)
m.drawmeridians(meridians)
title('Sinusoidal Filled Contour Demo')
show()
Beispiel #32
0
from matplotlib.toolkits.basemap import Basemap
from pylab import *
# read in topo data (on a regular lat/lon grid)
etopo = array(load('etopo20data.gz'), 'd')
lons = array(load('etopo20lons.gz'), 'd')
lats = array(load('etopo20lats.gz'), 'd')
# create Basemap instance for Robinson projection.
m = Basemap(projection='robin', lon_0=0.5 * (lons[0] + lons[-1]))
# create figure with same aspect ratio as map.
fig = m.createfigure()
# make filled contour plot.
x, y = m(*meshgrid(lons, lats))
cs = m.contourf(x, y, etopo, 30, cmap=cm.jet)
# draw coastlines.
m.drawcoastlines()
# draw a line around the map region.
m.drawmapboundary()
# draw parallels and meridians.
m.drawparallels(arange(-60., 90., 30.), labels=[1, 0, 0, 0])
m.drawmeridians(arange(0., 420., 60.), labels=[0, 0, 0, 1])
# add a title.
title('Robinson Projection')
show()
Beispiel #33
0
nframe = 0
n1 = 10
l, b, w, h = ax.get_position()
# loop over times, make contour plots, draw coastlines,
# parallels, meridians and title.
for nt, date in enumerate(datelabels[1:]):
    CS = m.contour(x,
                   y,
                   slp[nt, :, :],
                   clevs,
                   linewidths=0.5,
                   colors='k',
                   animated=True)
    CS = m.contourf(x,
                    y,
                    slp[nt, :, :],
                    clevs,
                    cmap=p.cm.RdBu_r,
                    animated=True)
    # plot wind vectors on lat/lon grid.
    # rotate wind vectors to map projection coordinates.
    #urot,vrot = m.rotate_vector(u[nt,:,:],v[nt,:,:],lons,lats)
    # plot wind vectors over map.
    #Q = m.quiver(x,y,urot,vrot,scale=500)
    # plot wind vectors on projection grid (looks better).
    # first, shift grid so it goes from -180 to 180 (instead of 0 to 360
    # in longitude).  Otherwise, interpolation is messed up.
    ugrid, newlons = shiftgrid(180., u[nt, :, :], longitudes, start=False)
    vgrid, newlons = shiftgrid(180., v[nt, :, :], longitudes, start=False)
    # transform vectors to projection grid.
    urot, vrot, xx, yy = m.transform_vector(ugrid,
                                            vgrid,
Beispiel #34
0
def plot_map(data, rlon=None, rlat=None, use_pcolor=0, **keywords):
    """ display  the data in a map
    keywords: dict which can include the following keywords  minv=0.0, maxv=0.0, dv=0.0,
    show_map=0, map_proj='cyl', show_lat=0, show_lon=0, lat_0=0.0, lon_0=0.0,
    minlat=-90.0, maxlat=90.0, minlon=0.0, maxlon=360.0, use_log=0, level=level
    """

    minv = 0.0
    if ('minv' in keywords):
        minv = keywords['minv']

    maxv = 0.0

    if ('maxv' in keywords):
        maxv = keywords['maxv']

    dv = 0.0
    if ('dv' in keywords):
        dv = keywords['dv']

    if ('dv' in keywords):
        dv = keywords['dv']

    if (maxv > minv):
        rlvl = arange(minv, maxv + dv, dv)
        rlvl[0] = -999.0
        rlvl[size(rlvl) - 1] = 999.

    stitle = ""
    add_str = ""
    if ('title' in keywords):
        add_str = keywords['title']
        add_str = add_str.strip()
        stitle = stitle + ' ' + add_str

    if ('unit' in keywords):
        add_str = keywords['unit']
        add_str = add_str.strip()
        stitle = stitle + '(' + add_str + ')'

    cbar_vert = 1
    if ('cbar_vert' in keywords):
        cbar_vert = keywords['cbar_vert']

    if (cbar_vert == 1):
        orientation = 'vertical'
    else:
        orientation = 'horizontal'

    show_lat = 1
    if ('show_lat' in keywords):
        show_lat = keywords['show_lat']

    show_lon = 1
    if ('show_lon' in keywords):
        show_lon = keywords['show_lon']

    nlon, nlat = shape(data)

    vals = array(data)

    map_proj = 'cyl'
    if ('map_proj' in keywords):
        map_proj = keywords['map_proj']

    lat_0 = 0.0
    if ('lat_0' in keywords):
        lat_0 = keywords['lat_0']

    minlat = -90.0
    maxlat = 90.0

    if ('minlat' in keywords):
        minlat = keywords['minlat']

    if ('maxlat' in keywords):
        maxlat = keywords['maxlat']

    if (rlat == None):
        dlat = (maxlat - minlat) / nlat
        rlat = arange(minlat, maxlat, dlat)

    minlon = -180
    maxlon = 180.0

    if ('minlon' in keywords):
        minlon = keywords['minlon']

    if ('maxlon' in keywords):
        maxlon = keywords['maxlon']

    if (rlon == None):
        dlon = (maxlon - minlon) / nlon
        rlon = arange(minlon, maxlon, dlon)

    lon_0 = 0

    do_bdr = 0
    if ('do_bdr' in keywords):
        do_bdr = keywords['do_bdr']

    if ('lon_0' in keywords):
        lon_0 = keywords['lon_0']

        boundinglat = 45

    if ('boundinglat' in keywords):
        boundinglat = keywords['boundinglat']

    if (map_proj == 'npstere' or map_proj == 'spstere'):
        m = Basemap(projection=map_proj, lon_0=lon_0, boundinglat=boundinglat)
    elif (map_proj == 'ortho'):
        m = Basemap(projection=map_proj, lon_0=lon_0, lat_0=lat_0)
    else:
        if (maxlon - minlon > 180):
            m=Basemap(llcrnrlon=minlon, llcrnrlat=minlat, \
                  urcrnrlon=maxlon, urcrnrlat=maxlat,projection=map_proj, lon_0=lon_0, lat_0=lat_0, resolution='l')
        else:
            m=Basemap(llcrnrlon=minlon, llcrnrlat=minlat, \
                          urcrnrlon=maxlon, urcrnrlat=maxlat,projection=map_proj, lon_0=lon_0, lat_0=lat_0, resolution='i')

    if (rlon[-1] < rlon[0] + 360.0):
        rlon = resize(rlon, nlon + 1)
        rlon[-1] = rlon[0] + 360.0
        vals = squeeze(vals)
        vals = resize(vals, [nlon + 1, nlat])

    x, y = m(*meshgrid(rlon, rlat))

    cmap = cm.Paired

    if ('cmap' in keywords):
        print 'cmap included'

        cmap = keywords['cmap']
    m.drawcoastlines(color='k', linewidth=0.5)

    if (maxv > minv):
        if (use_pcolor == 1):
            cs0 = m.pcolormesh(x,
                               y,
                               transpose(vals),
                               shading='flat',
                               vmin=minv,
                               vmax=maxv,
                               cmap=cmap)
            # cs0=m.imshow(x, y, transpose(vals),  shading='flat', vmin=minv, vmax=maxv, cmap=cmap)

        else:
            cs0 = m.contourf(x, y, transpose(vals), rlvl, cmap=cmap)
    else:
        if (use_pcolor == 1):
            cs0 = m.pcolor(x, y, transpose(vals), shading='flat', cmap=cmap)
        else:
            cs0 = m.contourf(x, y, transpose(vals), cmap=cmap)

    # info(m.drawcoastlines)
    # m.drawcountries(color=white)
    m.drawmapboundary()
    if (show_lat == 1):
        if (maxlat - minlat >= 90):
            m.drawparallels(arange(minlat, maxlat + 30.0, 30.),
                            labels=[1, 0, 0, 0],
                            color='grey')
        else:
            m.drawparallels(arange(minlat, maxlat + 5.0, 5.),
                            labels=[1, 0, 0, 0],
                            color='grey')

    if (show_lon == 1):
        if (maxlon - minlon >= 180):
            m.drawmeridians(arange(minlon, maxlon + 60, 60.),
                            labels=[0, 0, 0, 1],
                            color='grey')
        else:
            m.drawmeridians(arange(minlon, maxlon + 10, 10.),
                            labels=[0, 0, 0, 1],
                            color='grey')
        title(stitle)
    show_colorbar = 1
    if ('cb' in keywords):
        show_colorbar = keywords['cb']
    if (show_colorbar == 1):
        colorbar(orientation=orientation, extend='both')
    if (do_bdr == 1):
        lvl = arange(max(vals.flat))
        print shape(x), shape(y), shape(vals)
        # cs2=m.contour(x[0:-1,:], y[0:-1,:], transpose(vals), lvl, colors='k', linewidth=0.5)

    return m
Beispiel #35
0
centerlon=-105.
# create Basemap instance for Lambert Conformal Conic projection.
m = Basemap(llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat,
            urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat,
            rsphere=6371200.,
            resolution='l',area_thresh=5000.,projection='lcc',
            lat_1=standardpar,lon_0=centerlon)
x, y = m(lons, lats)
# create figure.
fig=figure(figsize=(8,8))
yoffset = (m.urcrnry-m.llcrnry)/30.
for npanel,fcsthr in enumerate(arange(0,72,12)):
    nt = fcsthrs.index(fcsthr)
    ax = fig.add_subplot(320+npanel+1)
    #cs = m.contour(x,y,t2m[nt,:,:],clevs,colors='k')
    cs = m.contourf(x,y,t2m[nt,:,:],clevs,cmap=cm.jet)
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.drawparallels(arange(25,75,20),labels=[1,0,0,0],fontsize=8,fontstyle='oblique')
    m.drawmeridians(arange(-140,0,20),labels=[0,0,0,1],fontsize=8,yoffset=yoffset,fontstyle='oblique')
    # panel title
    title(repr(fcsthr)+'-h forecast valid '+verifdates[nt],fontsize=12)
# figure title
figtext(0.5,0.95,u"2-m temp (\N{DEGREE SIGN}K) forecasts from %s"%verifdates[0],
        horizontalalignment='center',fontsize=14)
# a single colorbar.
cax = axes([0.1, 0.03, 0.8, 0.025])
colorbar(cax=cax, orientation='horizontal')
show()
Beispiel #36
0
# read in topo data (on a regular lat/lon grid)
# longitudes go from 20 to 380.
etopo = load('etopo20data.gz')
lons = load('etopo20lons.gz')
lats = load('etopo20lats.gz')
# create figure.
fig = Figure()
canvas = FigureCanvas(fig)
# create axes instance, leaving room for colorbar at bottom.
ax = fig.add_axes([0.125,0.175,0.75,0.75])
# create Basemap instance for Robinson projection.
# set 'ax' keyword so pylab won't be imported.
m = Basemap(projection='robin',lon_0=0.5*(lons[0]+lons[-1]),ax=ax)
# make filled contour plot.
x, y = m(*meshgrid(lons, lats))
cs = m.contourf(x,y,etopo,30,cmap=cm.jet)
# draw coastlines.
m.drawcoastlines()
# draw a line around the map region.
m.drawmapboundary()
# draw parallels and meridians.
m.drawparallels(nx.arange(-60.,90.,30.),labels=[1,0,0,0],fontsize=10)
m.drawmeridians(nx.arange(0.,420.,60.),labels=[0,0,0,1],fontsize=10)
# add a title.
ax.set_title('Robinson Projection')
# add a colorbar.
l,b,w,h = ax.get_position()
cax = fig.add_axes([l, b-0.1, w, 0.03],frameon=False) # setup colorbar axes
fig.colorbar(cs, cax=cax, orientation='horizontal',ticks=cs.levels[::3]) 
# save image (width 800 pixels with dpi=100 and fig width 8 inches).
canvas.print_figure('simpletest',dpi=100)
Beispiel #37
0
lons[-1] = lonsin[-1]+0.5*delon
lats[0:len(latsin)] = latsin-0.5*delat
lats[-1] = latsin[-1]+0.5*delat

# setup of basemap ('ortho' = orthographic projection)
m = Basemap(projection='ortho',
            resolution='c',area_thresh=10000.,lat_0=30,lon_0=-60)
xsize = rcParams['figure.figsize'][0]
fig=figure(figsize=(xsize,m.aspect*xsize))
ax = fig.add_axes([0.1,0.1,0.7,0.7],frameon=False)
# pcolor plot (slow)
#x,y = m(*meshgrid(lons,lats))
#p = m.pcolor(x,y,topodatin,shading='flat')
# filled contours (faster)
x,y = m(*meshgrid(lonsin,latsin))
levels, colls = m.contourf(x,y,topodatin,20,cmap=cm.jet,colors=None)
cax = axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes
colorbar(tickfmt='%d', cax=cax) # draw colorbar
axes(ax)  # make the original axes current again
# draw coastlines and political boundaries.
m.drawcoastlines()
# draw parallels and meridians (labelling is 
# not implemented for orthographic).
parallels = arange(-80.,90,20.)
m.drawparallels(parallels)
meridians = arange(0.,360.,20.)
m.drawmeridians(meridians)
# draw boundary around map region.
m.drawmapboundary()
title('Orthographic')
print 'plotting Orthographic example, close plot window to proceed ...'