예제 #1
0
파일: hplot.py 프로젝트: citterio/physplit
def InvokeMap(coastfile='/media/sda4/map-data/aust-coast-noaa-2000000-1.dat',
		    lllon=80,
		    urlon=166,
		    lllat=-47,
		    urlat=-9,
		    draw_map=True):
    global PYLIB_PATH

    map = Basemap(projection='cyl',
			llcrnrlon=lllon,
			urcrnrlon=urlon,
			llcrnrlat=lllat,
			urcrnrlat=urlat,
			#lat_ts=-35,
			lat_0=-35,
			lon_0=120,
			resolution='l',
			area_thresh=1000.)


    try: 
	coast = p.load(coastfile)
	coast = p.load(coastfile)
	coast_x,coast_y = map(coast[:,0],coast[:,1])
	p.plot(coast_x,coast_y,color='black')    
    except IOError:
	map.drawcoastlines()

    map.drawmapboundary()
    map.drawmeridians(p.arange(0,360,10),labels=[0,0,1,0])
    map.drawparallels(p.arange(-90,0,10),labels=[1,0,0,0])

    return map
예제 #2
0
def doit():
    map = Basemap(projection='lcc',
		    llcrnrlon=80,
		    urcrnrlon=160,
		    llcrnrlat=-50,
		    urcrnrlat=-8,
		    #lat_ts=-35,
		    lat_0=-35,
		    lon_0=120,
		    resolution='c',
		    area_thresh=1000.)
    p.clf()
    map.drawcoastlines()
    # map.drawcountries()
    
    # map.drawrivers()

    map.drawmeridians(p.arange(0,360,10),labels=[0,0,1,0])
    map.drawparallels(p.arange(-90,0,10),labels=[1,0,0,0])

    traj=p.load('example_traj.dat')
    coast=p.load('/media/sda4/map-data/aust-coast-noaa-2000000-1.dat')

    traj_x,traj_y   = map(traj[:,1],traj[:,0]) 
    # coast_x,coast_y = map(coast[:,0],coast[:,1])
    
    p.plot(traj_x,traj_y)    
    p.plot(coast_x,coast_y,color='black')    

    map.drawmapboundary()
    p.show()
    return map 
def draw_client_density():

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

    # plot them as filled circles on the map.
    # first, create a figure.
    dpi=100
    dimx=800/dpi
    dimy=400/dpi
    fig=figure(figsize=(dimx,dimy), dpi=dpi, frameon=False, facecolor='blue')
#    ax=fig.add_axes([0.1,0.1,0.7,0.7],axisbg='g')
    ax=fig.add_axes([0.0,0.0,1.0,1.0],axisbg='g')
    canvas = FigureCanvas(fig)
    results = lookup_client_locations()
    X,Y,Z = find_client_density(m,results)
#    s = random.sample(results, 40000)
#    for t in s:
#        lat=t[2]
#        lon=t[3]
#        # draw a red dot at the center.
#        xpt, ypt = m(lon, lat)
#        m.plot([xpt],[ypt],'ro', zorder=10)
    # draw coasts and fill continents.
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.drawlsmask([100,100,100,0],[0,0,255,255])
#    m.fillcontinents(color='green')
    palette = cm.YlOrRd
    m.imshow(Z,palette,extent=(m.xmin,m.xmax,m.ymin,m.ymax),interpolation='gaussian',zorder=0)
#    l,b,w,h = ax.get_position()
#    cax = axes([l+w+0.075, b, 0.05, h])
#    colorbar(cax=cax) # draw colorbar

    canvas.print_figure(outdir+'/clientmap.png', dpi=100)
예제 #4
0
ll_lat = -35.55
ur_lon = 48.45
ur_lat = 0.2
lon_0 = 0.0
satellite_height = 35785831.0

fig = figure(figsize=(7,7))
ax = fig.add_axes((0.1,0.1,0.8,0.8))
# create Basemap instance for a Geostationary projection.
m = Basemap(projection='geos', lon_0=lon_0, satellite_height=satellite_height,
            resolution='l', llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat)
# add data
m.imshow(data, cmap=cm.gray, interpolation='nearest')
clim(0, 255)
# draw coastlines.
m.drawcoastlines(linewidth=0.5, color=overlay_color)
m.drawcountries(linewidth=0.5, color=overlay_color)
# can't label meridians on bottom, because labels would
# be outside map projection region.
m.drawmeridians(arange(10,76,5), labels=[0,0,1,0], color=overlay_color)
m.drawparallels(arange(-90,90,5), labels=[1,0,0,0], color=overlay_color)
# add a colobar
#colorbar()
# add timestamp and save
fig = gcf()
fig.text(x=0.275, y=0.025, s=u'Meteosat-9 VIS 0.6 channel - 12:00 UTC 04/06/2007\n    \N{COPYRIGHT SIGN} EUMETSAT 2007',
            horizontalalignment='left',
            verticalalignment='bottom',
            fontsize=10,
            fontweight='bold',
            bbox=dict(facecolor='gray', alpha=0.25, pad=15))
예제 #5
0
xx = []
yy = []
for xi, yi in zip(x, y):
    if (xi > m.llcrnrx and xi < m.urcrnrx) and (yi > m.llcrnry
                                                and yi < m.urcrnry):
        xx.append(xi)
        yy.append(yi)
# plot them as filled circles on the map.
# first, create figure with same aspect ratio as map.
fig = m.createfigure()
# background color will be used for 'wet' areas.
fig.add_axes([0.1, 0.1, 0.8, 0.8], axisbg='aqua')
# use zorder=10 to make sure markers are drawn last.
# (otherwise they are covered up when continents are filled)
m.scatter(xx, yy, marker='o', c='k', s=25, zorder=10)
# draw coasts and fill continents.
m.drawcoastlines(linewidth=0.5)
m.fillcontinents(color='coral')
# draw parallels and meridians.
delat = 20.
circles = arange(0.,90.,delat).tolist()+\
          arange(-delat,-90,-delat).tolist()
m.drawparallels(circles)
delon = 45.
meridians = arange(0, 360, delon)
m.drawmeridians(meridians, labels=[1, 1, 1, 1])
title('Randomly Spaced Locations (Min Dist = %g km, %g points)' %
      (rcrit, len(lons_out)),
      y=1.075)
show()
예제 #6
0
rgba = rgba.astype(P.Float32)/255. # convert to normalized floats.

# define lat/lon grid that image spans (projection='cyl').
nlons = rgba.shape[1]; nlats = rgba.shape[0]
delta = 360./float(nlons)
lons = P.arange(-180.+0.5*delta,180.,delta)
lats = P.arange(-90.+0.5*delta,90.,delta)

# create new figure
fig=P.figure()
# define cylindrical equidistant projection.
m = Basemap(projection='cyl',llcrnrlon=-180,llcrnrlat=-90,urcrnrlon=180,urcrnrlat=90,resolution='l')
# plot (unwarped) rgba image.
im = m.imshow(rgba)
# draw coastlines.
m.drawcoastlines(linewidth=0.5,color='0.5')
# draw lat/lon grid lines.
m.drawmeridians(P.arange(-180,180,60),labels=[0,0,0,1],color='0.5')
m.drawparallels(P.arange(-90,90,30),labels=[1,0,0,0],color='0.5')
P.title("Blue Marble image - native 'cyl' projection",fontsize=12)
print 'plot cylindrical map (no warping needed) ...'

# create new figure
fig=P.figure()
# define orthographic projection centered on North America.
m = Basemap(projection='ortho',lat_0=40,lon_0=40,resolution='l')
# transform to nx x ny regularly spaced native projection grid
# nx and ny chosen to have roughly the same horizontal res as original image.
dx = 2.*P.pi*m.rmajor/float(nlons)
nx = int((m.xmax-m.xmin)/dx)+1; ny = int((m.ymax-m.ymin)/dx)+1
rgba_warped = ma.zeros((ny,nx,4),P.Float64)
예제 #7
0
 from pyroms.focus import Focus
 
 m = Basemap(projection='lcc', 
             resolution='i',
             llcrnrlon=5.0,
             llcrnrlat= 52.,
             urcrnrlon=35.5,
             urcrnrlat=68.0,
             lat_0=15.00, 
             lon_0=0.0,
             suppress_ticks=False)
 
 fig=pl.figure()
 # background color will be used for 'wet' areas.
 fig.add_axes([0.1,0.1,0.8,0.8],axisbg='azure')
 m.drawcoastlines(linewidth=0.25)
 m.fillcontinents(color='beige')
 
 x, y, beta = zip(*[(241782.65384467551, 1019981.3539730886,   1.0),
                    (263546.12512432877,  686274.79435173667,  0),
                    (452162.87621465814,  207478.42619936226,  1.0),
                    (1431519.0837990609,  432367.62942244718,  1.0),
                    (1409755.6125194072,  816855.62202965701, -1.0),
                    (1612881.344462839,   816855.62202965701,  1.0),
                    (1620135.83488939,   1194089.1242103155,  -1.0),
                    (2048150.7700559068, 1302906.4806085825,   1.0),
                    (1982860.3562169466, 1520541.1934051164,   1.0),
                    (1358974.1795335496, 1447996.2891396051,  -1.0),
                    (1344465.1986804469, 1716412.4349219969,   0),
                    (1620135.83488939,   2318535.1403257404,   1.0),
                    (1199375.3901494243, 2383825.5541647007,   1.0),
예제 #8
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
예제 #9
0
res = 'i'
map = Basemap(projection=prj,
              llcrnrlon=lonmin,
              llcrnrlat=latmin,
              urcrnrlon=lonmax,
              urcrnrlat=latmax,
              resolution=res)

map.plot(lon, lat, 'r-')
map.plot(lon, lat, 'k+')

fs = 10

pylab.text(115.9,-31.9, "Perth", fontsize=fs, ha='left', va='top')
pylab.text(114.1,-21.9, "Exmouth", fontsize=fs, ha='left', va='top')
pylab.text(118.5,-20.4, "Port Hedland", fontsize=fs, ha='left', va='top')
pylab.text(130.8,-12.6, "Darwin", fontsize=fs, ha='left', va='top')
pylab.text(145.75,-16.9, "Cairns", fontsize=fs, ha='right', va='top')
pylab.text(149.2,-21.2, "Mackay", fontsize=fs, ha='right', va='top')
pylab.text(153.0,-27.5, "Brisbane", fontsize=fs, ha='right', va='top')
pylab.text(153.1,-30.25, "Coffs Harbour", fontsize=fs, ha='right', va='top')
pylab.text(151.1,-33.9, "Sydney", fontsize=fs, ha='right', va='top')
pylab.text(150.5,-35.3, "Ulladulla", fontsize=fs, ha='right', va='top')
map.fillcontinents(color='0.9')
map.drawcoastlines()
map.drawparallels(parallel, label=[1,0,0,1], fontsize=8)
map.drawmeridians(meridian, label=[1,0,0,1], fontsize=8)
pylab.show()

pylab.savefig("N:\\cyclone\\sandpits\\carthur\\landfall\\gates.v0.2.png")
예제 #10
0
def plot_track(rlon, rlat=None, m=None, **keywords):
    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']

    if (m is None):
        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']

        minlon = -180
        maxlon = 180.0

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

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

        lon_0 = 0

        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 (show_lat == 1):
            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])
    sgn = 'o'
    if ('sgn' in keywords):
        sgn = keywords['sgn']

    if ('color' in keywords):
        print('I am here', size(rlon))

        lcolor = keywords['color']
        print(max(lcolor), min(lcolor))

        if ('minv' in keywords):
            vmin = keywords['minv']
        else:
            vmin = min(lcolor)

        if ('maxv' in keywords):
            vmax = keywords['maxv']
        else:
            vmax = max(lcolor)

        cx = cm.jet
        cx.set_over('r')
        cx.set_under('w')
        x, y = m(rlon, rlat)

        if (len(rlon) < 100):
            scatter(x,
                    y,
                    marker=sgn,
                    c=lcolor,
                    s=30.0,
                    color='w',
                    vmin=vmin,
                    vmax=vmax,
                    cmap=cx)  # , markersize=11)
        else:
            scatter(x,
                    y,
                    marker=sgn,
                    c=lcolor,
                    s=26,
                    edgecolor='w',
                    vmin=vmin,
                    vmax=vmax,
                    cmap=cx)  # , markersize=6)

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

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

    show_colorbar = 0
    if ('cb' in keywords):
        show_colorbar = keywords['cb']
    if (show_colorbar == 1):
        colorbar(orientation=orientation)

    # colorbar(cmap=cx)

    m.drawcoastlines(color='k', linewidth=1.0)
    m.drawmapboundary()
    # m.drawcountries(color='k', linewidth=0.5)

    if ('title' in keywords):
        stitle = keywords['title']
        title(stitle)

    return m
예제 #11
0
파일: plot.py 프로젝트: jwblin/qtcm
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'
예제 #12
0
x_bm,y_bm = ps2.to_basemap_xy(m2, x_grid / cm_per_m, y_grid / cm_per_m)
#Radius factor used in all of the analyses
R = 4.32

heights_cress = oban.analyze_grid(data.heights, x_grid, y_grid, data.x, data.y,
  oban.cressman_weights, R)
contours = N.arange(5300., 6000., 60.0)
parallels = N.arange(25., 60.0, 10.0)
meridians = N.arange(-120., -60.0, 10.0)

##m2.drawstates()
##m2.drawcountries()
##m2.drawcoastlines()
##m2.drawparallels(parallels, labels = [1,1,0,0])
##m2.drawmeridians(meridians, labels = [0,0,1,1])
ob_x, ob_y = ps2.to_basemap_xy(m2, data.x / cm_per_m, data.y / cm_per_m)
#m2.plot(ob_x, ob_y, 'bx')
#m2.plot(x_bm, y_bm, 'g.')
for name in M.cm.cmapnames:
  f = P.figure()
  m2.drawstates()
  m2.drawcountries()
  m2.drawcoastlines()
  m2.drawparallels(parallels, labels = [1,1,0,0])
  m2.drawmeridians(meridians, labels = [0,0,1,1])
  c = m2.contour(x_bm, y_bm, heights_cress, contours, cmap=M.cm.get_cmap(name))
  P.title(name)
  #P.clabel(c)
  P.show()
예제 #13
0
# 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)')

# panel 2
msh = Basemap(lon_0=-105,boundinglat=-20.,
             resolution='c',area_thresh=10000.,projection='splaea')
xsh,ysh = msh(lons,lats)
ax = fig.add_subplot(212)
CS = msh.contour(xsh,ysh,hgt,15,linewidths=0.5,colors='k')
예제 #14
0
fig = figure(figsize=(7, 7))
ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
# create Basemap instance for a Geostationary projection.
m = Basemap(projection='geos',
            lon_0=lon_0,
            satellite_height=satellite_height,
            resolution='l',
            llcrnrlon=ll_lon,
            llcrnrlat=ll_lat,
            urcrnrlon=ur_lon,
            urcrnrlat=ur_lat)
# add data
m.imshow(data, cmap=cm.gray, interpolation='nearest')
clim(0, 255)
# draw coastlines.
m.drawcoastlines(linewidth=0.5, color=overlay_color)
m.drawcountries(linewidth=0.5, color=overlay_color)
# can't label meridians on bottom, because labels would
# be outside map projection region.
m.drawmeridians(arange(10, 76, 5), labels=[0, 0, 1, 0], color=overlay_color)
m.drawparallels(arange(-90, 90, 5), labels=[1, 0, 0, 0], color=overlay_color)
# add a colobar
#colorbar()
# add timestamp and save
fig = gcf()
fig.text(
    x=0.275,
    y=0.025,
    s=
    u'Meteosat-9 VIS 0.6 channel - 12:00 UTC 04/06/2007\n    \N{COPYRIGHT SIGN} EUMETSAT 2007',
    horizontalalignment='left',
예제 #15
0
#Do the necessary processing for each analysis
contours = N.arange(5300., 6000., 60.0)
parallels = N.arange(25., 60.0, 10.0)
meridians = N.arange(-120., -60.0, 10.0)
fields = (cress1, cress2, cress3, cress_187, barnes_analyses[0],
  barnes_analyses[1], barnes_analyses[2], barnes_3pass)
names = ('Cressman 1st Pass', 'Cressman 2nd Pass', 'Cressman 3rd Pass',
  'Cressman R=1.87d', r'$\rm{Barnes} \gamma=1.0$',r'$\rm{Barnes} \gamma=0.4$',
  r'$\rm{Barnes} \gamma=0.2$', r'$\rm{Barnes 3-pass} \gamma=1.0$')
filenames = ('cress1', 'cress2', 'cress3', 'cress187', 'barnes1', 'barnes2',
  'barnes3', 'barnes3pass')
for field,name,filename in zip(fields, names, filenames):
  f = P.figure()
  bm_ps.drawstates()
  bm_ps.drawcountries()
  bm_ps.drawcoastlines()
  bm_ps.drawparallels(parallels, labels = [1,1,0,0])
  bm_ps.drawmeridians(meridians, labels = [0,0,1,1])
  cp = bm_ps.contour(x_bm, y_bm, field, contours, cmap=colormap)
  P.clabel(cp, fontsize=fontsize, fmt='%.1f')
  f.text(0.5,0.95,name,horizontalalignment='center',fontsize=16)
  if save_work:
    P.savefig(filename + '.png', dpi = 300)
  else:
    P.show()

filename = 'cress12diff'
f = P.figure()
bm_ps.drawstates()
bm_ps.drawcountries()
bm_ps.drawcoastlines()
예제 #16
0
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
delon = 30.
meridians = arange(10.,360.,delon)
npanel = 0
# plots of the US.
projs = ['lcc','aeqd','aea','laea','eqdc','stere']
fig = figure(figsize=(8,12))
for proj in projs:
    m = Basemap(width=width,height=height,
                resolution='c',projection=proj,\
                lat_0=lat_0,lon_0=lon_0)
    npanel = npanel + 1
    subplot(3,2,npanel)
    # setup figure with same aspect ratio as map.
    m.drawcoastlines()
    m.drawcountries()
    m.fillcontinents()
    m.drawstates()
    m.drawparallels(circles)
    m.drawmeridians(meridians)
    title('proj = '+proj+' centered on %sW, %sN' % (lon_0,lat_0),fontsize=10)
show()

proj = 'omerc'
delat = 10.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
delon = 10.
meridians = arange(10.,360.,delon)
lat_1 = 40; lat_2 = 55
예제 #17
0
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
msh = Basemap(lon_0=-105, boundinglat=-20.0, resolution="c", area_thresh=10000.0, projection="splaea")
xsh, ysh = msh(lons, lats)
ax = fig.add_subplot(212)
CS = msh.contour(xsh, ysh, hgt, 15, linewidths=0.5, colors="k")
CS = msh.contourf(xsh, ysh, hgt, 15, cmap=P.cm.Spectral)
# colorbar on bottom.
예제 #18
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
예제 #19
0
print 'min/max etopo20 data:'
print min(ravel(topoin)), max(ravel(topoin))

m = Basemap(lons[0],lats[0],lons[-1],lats[-1],\
            resolution='c',area_thresh=10000.,projection='cyl')
xsize = rcParams['figure.figsize'][0]
fig = figure(figsize=(xsize, m.aspect * xsize))
ax = fig.add_axes([0.1, 0.1, 0.75, 0.75])
im = imshow(topoin,
            cm.jet,
            extent=(m.llcrnrx, m.urcrnrx, m.llcrnry, m.urcrnry),
            origin='lower')
cax = axes([0.875, 0.1, 0.05, 0.75])
colorbar(tickfmt='%d', cax=cax)  # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines(ax)
#m.drawcountries(ax)
#m.drawstates(ax)
#m.fillcontinents(ax)
# draw parallels
delat = 30.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(ax, circles)
# draw meridians
delon = 60.
lon1 = int(lons[0] / delon) * delon
lon2 = (int(lons[-1] / delon) + 1) * delon
meridians = arange(lon1, lon2, delon)
m.drawmeridians(ax, meridians)
ax.set_xticks([])  # no ticks
예제 #20
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'
예제 #21
0
res = 'i'
map = Basemap(projection=prj,
              llcrnrlon=lonmin,
              llcrnrlat=latmin,
              urcrnrlon=lonmax,
              urcrnrlat=latmax,
              resolution=res)

map.plot(lon, lat, 'r-')
map.plot(lon, lat, 'k+')

fs = 10

pylab.text(115.9,-31.9, "Perth", fontsize=fs, ha='left', va='top')
pylab.text(114.1,-21.9, "Exmouth", fontsize=fs, ha='left', va='top')
pylab.text(118.5,-20.4, "Port Hedland", fontsize=fs, ha='left', va='top')
pylab.text(130.8,-12.6, "Darwin", fontsize=fs, ha='left', va='top')
pylab.text(145.75,-16.9, "Cairns", fontsize=fs, ha='right', va='top')
pylab.text(149.2,-21.2, "Mackay", fontsize=fs, ha='right', va='top')
pylab.text(153.0,-27.5, "Brisbane", fontsize=fs, ha='right', va='top')
pylab.text(153.1,-30.25, "Coffs Harbour", fontsize=fs, ha='right', va='top')
pylab.text(151.1,-33.9, "Sydney", fontsize=fs, ha='right', va='top')
pylab.text(150.5,-35.3, "Ulladulla", fontsize=fs, ha='right', va='top')
map.fillcontinents(color='0.9')
map.drawcoastlines()
map.drawparallels(parallel, label=[1,0,0,1], fontsize=8)
map.drawmeridians(meridian, label=[1,0,0,1], fontsize=8)
pylab.show()

pylab.savefig("N:\\cyclone\\sandpits\\carthur\\landfall\\gates.v0.2.png")
예제 #22
0
from matplotlib.toolkits.basemap import Basemap
import pylab as p
# set up orthographic map projection with
# perspective of satellite looking down at 50N, 100W.
# use low resolution coastlines.
map = Basemap(projection='ortho', lat_0=50, lon_0=-100, resolution='l')
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral')
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary()
# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(p.arange(0, 360, 30))
map.drawparallels(p.arange(-90, 90, 30))
# lat/lon coordinates of five cities.
lats = [40.02, 32.73, 38.55, 48.25, 17.29]
lons = [-105.16, -117.16, -77.00, -114.21, -88.10]
cities = [
    'Boulder, CO', 'San Diego, CA', 'Washington, DC', 'Whitefish, MT',
    'Belize City, Belize'
]
# compute the native map projection coordinates for cities.
x, y = map(lons, lats)
# plot filled circles at the locations of the cities.
map.plot(x, y, 'bo')
# plot the names of those five cities.
for name, xpt, ypt in zip(cities, x, y):
    p.text(xpt + 50000, ypt + 50000, name, fontsize=9)
# make up some data on a regular lat/lon grid.
nlats = 73
예제 #23
0
def plot_track(rlon, rlat=None, m=None, **keywords):
    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']

    if (m == None):
        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']

        minlon = -180
        maxlon = 180.0

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

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

        lon_0 = 0

        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 (show_lat == 1):
            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])
    sgn = '+'
    if ('sgn' in keywords):
        sgn = keywords['sgn']
    if ('color' in keywords):
        lcolor = keywords['color']
        if (len(rlon) < 100):
            m.plot(rlon, rlat, sgn, color=lcolor, markersize=11)
        else:
            m.plot(rlon, rlat, sgn, color=lcolor, markersize=6)

    else:
        m.plot(rlon, rlat, sgn)

    m.drawcoastlines(color='w', linewidth=0.5)
    m.drawmapboundary()
    # m.drawcountries(color='k', linewidth=0.5)

    if ('title' in keywords):
        stitle = keywords['title']
        title(stitle)

    return m
예제 #24
0
nlats = rgba.shape[0]
delta = 360. / float(nlons)
lons = P.arange(-180. + 0.5 * delta, 180., delta)
lats = P.arange(-90. + 0.5 * delta, 90., delta)

# define cylindrical equidistant projection.
m = Basemap(projection='cyl',
            llcrnrlon=-180,
            llcrnrlat=-90,
            urcrnrlon=180,
            urcrnrlat=90,
            resolution='l')
# plot (unwarped) rgba image.
im = m.imshow(rgba)
# draw coastlines.
m.drawcoastlines(linewidth=0.5, color='0.5')
# draw lat/lon grid lines.
m.drawmeridians(P.arange(-180, 180, 60), labels=[0, 0, 0, 1], color='0.5')
m.drawparallels(P.arange(-90, 90, 30), labels=[1, 0, 0, 0], color='0.5')
P.title("Blue Marble image - native 'cyl' projection", fontsize=12)
P.show()

# define orthographic projection centered on North America.
m = Basemap(projection='ortho', lat_0=40, lon_0=40, resolution='l')
# transform to nx x ny regularly spaced native projection grid
# nx and ny chosen to have roughly the same horizontal res as original image.
dx = 2. * P.pi * m.rmajor / float(nlons)
nx = int((m.xmax - m.xmin) / dx) + 1
ny = int((m.ymax - m.ymin) / dx) + 1
rgba_warped = ma.zeros((ny, nx, 4), P.Float64)
# interpolate rgba values from proj='cyl' (geographic coords) to 'lcc'
예제 #25
0
import matplotlib
from matplotlib.toolkits.basemap import Basemap
from pylab import *

# setup a mercator projection.
m = Basemap(-90.,30.,30.,60.,\
            resolution='c',area_thresh=10000.,projection='merc',\
            lat_ts=20.)
xsize = rcParams['figure.figsize'][0]
fig=figure(figsize=(xsize,m.aspect*xsize))
fig.add_axes([0.1,0.1,0.8,0.8])
ax = gca() # get current axis instance
ax.update_datalim(((m.llcrnrx, m.llcrnry),(m.urcrnrx,m.urcrnry)))
ax.set_xlim((m.llcrnrx, m.urcrnrx))
ax.set_ylim((m.llcrnry, m.urcrnry))
m.drawcoastlines(ax)
m.fillcontinents(ax)
# draw parallels
circles = [35,45,55]
m.drawparallels(ax,circles,labels=[1,1,0,1])
# draw meridians
meridians = [-90,-60,-30,0,30]
m.drawmeridians(ax,meridians,labels=[1,1,0,1])
# nylat, nylon are lat/lon of New York
nylat = 40.78
nylon = -73.98
# lonlat, lonlon are lat/lon of London.
lonlat = 51.53
lonlon = 0.08
# draw the great circle.
m.drawgreatcircle(ax,nylon,nylat,lonlon,lonlat,linewidth=2,color='b')
예제 #26
0
    def makeFigure(self):
        """
        :todo: Uses pylab so may not be threadsafe.
        """

        lon = self.grid.lon0 + N.arrayrange(self.grid.nlon) * self.grid.dlon
        lat = self.grid.lat0 + N.arrayrange(self.grid.nlat) * self.grid.dlat

        ll_lon, ll_lat = lon[0], lat[0]
        ur_lon, ur_lat = lon[-1], lat[-1]

        # Account for variable lat/lon axis ordering
        #!TODO: Could we move this (along with the equivilent in render_imp.py into grid.py?
        if self.grid.ilat < self.grid.ilon:
            latLonOrdering = True
        else:
            latLonOrdering = False

        if latLonOrdering:
            var = self.grid.value
        else:
            var = MA.transpose(self.grid.value)

        fig = p.figure()
        map = Basemap(projection='cyl',
                      llcrnrlon=ll_lon,
                      llcrnrlat=ll_lat,
                      urcrnrlon=ur_lon,
                      urcrnrlat=ur_lat,
                      resolution='l')

        ##         if self.grid.units:
        ##             p.title("%s\n(%s)" % (self.grid.long_name, self.grid.units))
        ##         else:
        ##             p.title(self.grid.long_name)
        p.title(self.grid.long_name)

        if self.type == 'colour':
            # transform_scalar doesn't support masked arrays so we must fill then replace the mask.
            var_dat = map.transform_scalar(var.filled(1.0e20), lon, lat,
                                           len(lon), len(lat))
            var = MA.masked_values(var_dat, 1.0e20)
            map.imshow(var,
                       cmap=self.cmap,
                       vmin=self.vmin,
                       vmax=self.vmax,
                       interpolation='nearest')
            cbar = p.colorbar(orientation='horizontal', format='%.2g')
            if self.grid.units:
                cbar.ax.set_xlabel(self.grid.units)

        else:
            x, y = map(*p.meshgrid(lon, lat))
            c = map.contour(x, y, var, 12, colors='black')
            c.clabel(fontsize=8)
            map.fillcontinents(color='#e0e0e0')

        map.drawcoastlines(color='gray')

        map.drawmeridians(p.arange(-180, 180, 30),
                          labels=[1, 0, 0, 1],
                          color='gray')
        map.drawparallels(p.arange(-90, 90, 15),
                          labels=[1, 0, 0, 1],
                          color='gray')

        # Wrap the caption
        caption = word_wrap(self.caption, 80)

        fig.text(0.1,
                 0.08,
                 caption,
                 fontsize=10,
                 horizontalalignment='left',
                 verticalalignment='top',
                 transform=fig.transFigure)

        return fig
예제 #27
0
xsize = rcParams['figure.figsize'][0]
fig = figure(figsize=(xsize, m.aspect * xsize))
fig.add_axes([0.1, 0.1, 0.8, 0.8])
# nylat, nylon are lat/lon of New York
nylat = 40.78
nylon = -73.98
# lonlat, lonlon are lat/lon of London.
lonlat = 51.53
lonlon = 0.08
# find 1000 points along the great circle.
#x,y = m.gcpoints(nylon,nylat,lonlon,lonlat,1000)
# draw the great circle.
#m.plot(x,y,linewidth=2)
# drawgreatcircle performs the previous 2 steps in one call.
m.drawgreatcircle(nylon, nylat, lonlon, lonlat, linewidth=2, color='b')
m.drawcoastlines()
m.fillcontinents()
# draw parallels
circles = arange(10, 90, 20)
m.drawparallels(circles, labels=[1, 1, 0, 1])
# draw meridians
meridians = arange(-180, 180, 30)
m.drawmeridians(meridians, labels=[1, 1, 0, 1])
title('Great Circle from New York to London (Mercator)')
show()

# setup a gnomonic projection.
m = Basemap(llcrnrlon=-100.,llcrnrlat=20.,urcrnrlon=20.,urcrnrlat=60.,\
            resolution='c',area_thresh=10000.,projection='gnom',\
            lat_0=40.,lon_0=-45.)
# make figure with aspect ratio that matches map region.
예제 #28
0
 #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.
 qk = p.quiverkey(Q, 0.1, 0.1, 20, '20 m/s', labelpos='W')
 # draw coastlines, parallels, meridians, title.
 m.drawcoastlines(linewidth=1.5)
 m.drawparallels(parallels)
 m.drawmeridians(meridians)
 p.title('SLP and Wind Vectors '+date)
 if nt == 0: # plot colorbar on a separate axes (only for first frame)
     cax = p.axes([l+w-0.05, b, 0.03, h]) # setup colorbar axes
     fig.colorbar(CS,drawedges=True, cax=cax) # draw colorbar
     cax.text(0.0,-0.05,'mb')
     p.axes(ax) # reset current axes
 p.draw() # draw the plot
 # save first and last frame n1 times 
 # (so gif animation pauses at beginning and end)
 if nframe == 0 or nt == slp.shape[0]-1:
    for n in range(n1):
        p.savefig('anim%03i'%nframe+'.png')
        nframe = nframe + 1
예제 #29
0
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)
# done.
print 'image saved in simpletest.png'
예제 #30
0
def wrf_grid(
  # WPS -> map_proj
  projection,
  # WPS -> truelat1
  lat_1,
  # WPS -> truelat2
  lat_2,
  # WPS -> stand_lon
  lon_0,
  # WPS -> ref_lat
  grid_centre_lat,
  # WPS -> ref_lon
  grid_centre_lon,
  delta_x,
  delta_y,
  # WPS -> e_we
  nx,
  # WPS -> e_sn
  ny,
  show_mass_grid = False,
  show_stag_grids = False,
  ):
    if lon_0 != grid_centre_lon:
        print 'not implemented yet -> see the source'
        print "\tbut let's try it anyways..."
        #return

    width   = nx * delta_x
    height  = ny * delta_y
    frame_x = 10 * delta_x
    frame_y = 10 * delta_y
    m = Basemap(
      lat_0 = grid_centre_lat,
      # this could be a bad assumption... because lon_0 and grid_centre_lon
      # need not be aligned, but at the same time I need to give this to
      # basemap for the grid to be centred... I could probably fix it
      # assigning lon_0 and then imposing a grid shift in native coordinates
      # if ref_lon and lon_0 were not the same
      lon_0 = lon_0,
      lat_1 = lat_1,
      lat_2 = lat_2,
      width = width + 2*frame_x,
      height = height + 2*frame_y,
      resolution = 'l',
      area_thresh=1000.
      )
    grid_centre_x, grid_centre_y = m(grid_centre_lon, grid_centre_lat)
    min_x = grid_centre_x - width/2.
    min_y = grid_centre_y - height/2.
    max_x = min_x + width
    max_y = min_y + height
    x = n.arange(min_x, max_x + a_small_number, delta_x)
    y = n.arange(min_y, max_y + a_small_number, delta_y)  
    x = x[1:-1]
    y = y[1:-1]
    x_u = n.arange(min_x, max_x + delta_x + a_small_number, delta_x)
    x_u -= delta_x/2.
    x_u = x_u[1:-1]
    y_v = n.arange(min_y, max_y + delta_y + a_small_number, delta_y)
    y_v -= delta_y/2.
    y_v = y_v[1:-1]
    X, Y = p.meshgrid(x,y)
    lon, lat = m(X, Y, inverse=True)
    X_u, Y_u = p.meshgrid(x_u,y)
    lon_u, lat_u = m(X_u, Y_u, inverse=True)
    X_v, Y_v = p.meshgrid(x,y_v)
    lon_v, lat_v = m(X_v, Y_v, inverse=True)
    if show_mass_grid:
        m.plot(X, Y, 'b+')
        m.plot([grid_centre_x], [grid_centre_y], 'r+')
        if show_stag_grids:
            m.plot(X_u, Y_u, 'g+')
            m.plot(X_v, Y_v, 'r+')
        m.drawcoastlines()
	p.show()
    output = {
      'map' : m,
      'mass_stag': {
        'lon_2d' : lon,
        'lat_2d' : lat,
        'x'      : x,
        'y'      : y,
        'x_2d'   : X,
        'y_2d'   : Y,
        }, 
      'u_stag': {
        'lon_2d' : lon_u,
        'lat_2d' : lat_u,
        'x'      : x_u,
        'y'      : y,
        'x_2d'   : X_u,
        'y_2d'   : Y_u,
        }, 
      'v_stag': {
        'lon_2d' : lon_v,
        'lat_2d' : lat_v,
        'x'      : x,
        'y'      : y_v,
        'x_2d'   : X_v,
        'y_2d'   : Y_v,
        } 
      }

    return output