예제 #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 
예제 #3
0
def draw_graph_on_map(g, node2weight, node2pos, pic_title,  pic_area=[-130,10,140,70], output_fname_prefix=None, need_draw_edge=0):
	"""
	2007-09-13
		identity_pair_ls is a list of pairs of strains (ecotype id as in table ecotype)
	2007-10-08
		correct a bug in 4*diameter_ls, diameter_ls has to be converted to array first.
		sqrt the node weight, 8 times the original weight
	"""
	import os, sys
	sys.stderr.write("Drawing graph on a map ...\n")
	import pylab, math
	from matplotlib.toolkits.basemap import Basemap
	pylab.clf()
	fig = pylab.figure()
	fig.add_axes([0.05,0.05,0.9,0.9])	#[left, bottom, width, height]
	m = Basemap(llcrnrlon=pic_area[0],llcrnrlat=pic_area[1],urcrnrlon=pic_area[2],urcrnrlat=pic_area[3],\
	resolution='l',projection='mill', ax=pylab.gca())
	
	sys.stderr.write("\tDrawing nodes ...")
	euc_coord1_ls = []
	euc_coord2_ls = []
	diameter_ls = []
	for n in g.nodes():
		lat, lon = node2pos[n]
		euc_coord1, euc_coord2 = m(lon, lat)	#longitude first, latitude 2nd
		euc_coord1_ls.append(euc_coord1)
		euc_coord2_ls.append(euc_coord2)
		diameter_ls.append(math.sqrt(node2weight[n]))
	import numpy
	diameter_ls = numpy.array(diameter_ls)
	m.scatter(euc_coord1_ls, euc_coord2_ls, 8*diameter_ls, marker='o', color='r', alpha=0.4, zorder=12, faceted=False)
	sys.stderr.write("Done.\n")
	
	if need_draw_edge:
		sys.stderr.write("\tDrawing edges ...")
		ax=pylab.gca()
		for popid1, popid2, no_of_connections in g.edges():
			lat1, lon1 = node2pos[popid1]
			lat2, lon2 = node2pos[popid2]
			x1, y1 = m(lon1, lat1)
			x2, y2 = m(lon2, lat2)
			ax.plot([x1,x2],[y1,y2], 'g', linewidth=math.log(no_of_connections+1)/2, alpha=0.2, zorder=10)
		sys.stderr.write("Done.\n")
	
	#m.drawcoastlines()
	m.drawparallels(pylab.arange(-90,90,30), labels=[1,1,0,1])
	m.drawmeridians(pylab.arange(-180,180,30), labels=[1,1,0,1])
	m.fillcontinents()
	m.drawcountries()
	m.drawstates()
	
	pylab.title(pic_title)
	if output_fname_prefix:
		pylab.savefig('%s.eps'%output_fname_prefix, dpi=600)
		pylab.savefig('%s.svg'%output_fname_prefix, dpi=600)
		pylab.savefig('%s.png'%output_fname_prefix, dpi=600)
	del fig, m, pylab
	sys.stderr.write("Done.\n")
예제 #4
0
	def draw_clustered_strain_location(self, label_ls, weighted_pos_ls, diameter_ls, label_type, label_type2label_name, pic_area=[-180,-90,180,90], output_fname_prefix=None, label_name=None):
		"""
		2007-07-11
		draw populations derived from connected_components of the strain network
		#each pie denotes a population, with diameter proportional to the size of the population
		#each pie labeled with the number of strains in that population
		2007-07-13
			use popid as label
		2007-07-17
			no parallels, no meridians
		2007-08-29
			copied from CreatePopulation.py
		2007-09-11
			add label name
		2007-10-14
			correct a bug in 5*diameter_ls. diameter_ls has to an array

		"""
		sys.stderr.write("Drawing population map...")
		import pylab
		from matplotlib.toolkits.basemap import Basemap
		pylab.clf()
		fig = pylab.figure()
		fig.add_axes([0.05,0.05,0.9,0.9])	#[left, bottom, width, height]
		m = Basemap(llcrnrlon=pic_area[0],llcrnrlat=pic_area[1],urcrnrlon=pic_area[2],urcrnrlat=pic_area[3],\
		resolution='l',projection='mill')
		
		euc_coord1_ls = []
		euc_coord2_ls = []
		ax=pylab.gca()
		for i in range(len(weighted_pos_ls)):
			lat, lon = weighted_pos_ls[i]
			euc_coord1, euc_coord2 = m(lon, lat)	#longitude first, latitude 2nd
			euc_coord1_ls.append(euc_coord1)
			euc_coord2_ls.append(euc_coord2)
			ax.text(euc_coord1, euc_coord2, str(label_ls[i]), size=5, alpha=0.5, horizontalalignment='center', verticalalignment='center', zorder=12)
		import numpy
		diameter_ls = numpy.array(diameter_ls)
		m.scatter(euc_coord1_ls, euc_coord2_ls, 5*diameter_ls, marker='o', color='r', alpha=0.3, zorder=10, faceted=False)
		
		#m.drawcoastlines()
		m.drawparallels(pylab.arange(-90,90,30), labels=[1,1,0,1])	#labels intersect the left, right, top bottom of the plot
		m.drawmeridians(pylab.arange(-180,180,30), labels=[1,1,0,1])
		m.fillcontinents()
		m.drawcountries()
		m.drawstates()
		pylab.title("worldwide distribution of %s populations, labeled by %s"%(len(weighted_pos_ls), label_type2label_name[label_type]))
		if output_fname_prefix:
			pylab.savefig('%s_pop_map.eps'%output_fname_prefix, dpi=300)
			pylab.savefig('%s_pop_map.svg'%output_fname_prefix, dpi=300)
			pylab.savefig('%s_pop_map.png'%output_fname_prefix, dpi=300)
		del m, pylab, Basemap
		sys.stderr.write("Done.\n")
예제 #5
0
    def DrawSiteNetwork(self,
                        g,
                        node_label2pos_counts,
                        pic_area=[-180, -90, 180, 90],
                        output_fname_prefix=None):
        """
		2007-07-17
			put ax.plot() right after Basemap() but after m.xxx() so that it'll zoom in
			use 'g' in ax.plot(), otherwise, ax.plot() alternates all colors.
			no parallels, no meridians
		2007-08-29 copied from CreatePopulation.py and renamed from DrawStrainNetwork
		"""
        sys.stderr.write("Drawing Site Network...")
        import pylab
        from matplotlib.toolkits.basemap import Basemap
        pylab.clf()
        fig = pylab.figure()
        fig.add_axes([0.05, 0.05, 0.9, 0.9])  #[left, bottom, width, height]
        m = Basemap(llcrnrlon=pic_area[0],llcrnrlat=pic_area[1],urcrnrlon=pic_area[2],urcrnrlat=pic_area[3],\
        resolution='l',projection='mill')

        ax = pylab.gca()
        for e in g.edges():
            lat1, lon1 = node_label2pos_counts[e[0]][0]
            lat2, lon2 = node_label2pos_counts[e[1]][0]
            x1, y1 = m(lon1, lat1)
            x2, y2 = m(lon2, lat2)
            ax.plot([x1, x2], [y1, y2], 'g', alpha=0.5, zorder=12)

        #m.drawcoastlines()
        m.drawparallels(pylab.arange(-90, 90, 30), labels=[1, 1, 0, 1])
        m.drawmeridians(pylab.arange(-180, 180, 30), labels=[1, 1, 0, 1])
        m.fillcontinents()
        m.drawcountries()
        m.drawstates()

        pylab.title("Network of strains")
        if output_fname_prefix:
            pylab.savefig('%s_site_network.eps' % output_fname_prefix, dpi=300)
            pylab.savefig('%s_site_network.svg' % output_fname_prefix, dpi=300)
            pylab.savefig('%s_site_network.png' % output_fname_prefix, dpi=300)
        del m, pylab, Basemap
        sys.stderr.write("Done.\n")
예제 #6
0
	def DrawSiteNetwork(self, g, node_label2pos_counts,pic_area=[-180,-90,180,90], output_fname_prefix=None):
		"""
		2007-07-17
			put ax.plot() right after Basemap() but after m.xxx() so that it'll zoom in
			use 'g' in ax.plot(), otherwise, ax.plot() alternates all colors.
			no parallels, no meridians
		2007-08-29 copied from CreatePopulation.py and renamed from DrawStrainNetwork
		"""
		sys.stderr.write("Drawing Site Network...")
		import pylab
		from matplotlib.toolkits.basemap import Basemap
		pylab.clf()
		fig = pylab.figure()
		fig.add_axes([0.05,0.05,0.9,0.9])	#[left, bottom, width, height]
		m = Basemap(llcrnrlon=pic_area[0],llcrnrlat=pic_area[1],urcrnrlon=pic_area[2],urcrnrlat=pic_area[3],\
		resolution='l',projection='mill')
		
		ax=pylab.gca()
		for e in g.edges():
			lat1, lon1 = node_label2pos_counts[e[0]][0]
			lat2, lon2 = node_label2pos_counts[e[1]][0]
			x1, y1 = m(lon1, lat1)
			x2, y2 = m(lon2, lat2)
			ax.plot([x1,x2],[y1,y2], 'g', alpha=0.5, zorder=12)
		
		#m.drawcoastlines()
		m.drawparallels(pylab.arange(-90,90,30), labels=[1,1,0,1])
		m.drawmeridians(pylab.arange(-180,180,30), labels=[1,1,0,1])
		m.fillcontinents()
		m.drawcountries()
		m.drawstates()

		pylab.title("Network of strains")
		if output_fname_prefix:
			pylab.savefig('%s_site_network.eps'%output_fname_prefix, dpi=300)
			pylab.savefig('%s_site_network.svg'%output_fname_prefix, dpi=300)
			pylab.savefig('%s_site_network.png'%output_fname_prefix, dpi=300)
		del m, pylab, Basemap
		sys.stderr.write("Done.\n")
예제 #7
0
# in which direction to depart for other points on earth and how far
# it will be to reach that destination.
# The specified point shows up as a red dot in the center of the map.

# This example shows how to use the width and height keywords
# to specify the map projection region (instead of specifying
# the lat/lon of the upper right and lower left corners).

# user enters the lon/lat of the point, and it's name
lon_0 = float(raw_input('input reference lon (degrees):'))
lat_0 = float(raw_input('input reference lat (degrees):'))
location = raw_input('name of location:')

# use these values to setup Basemap instance.
width = 28000000
m = Basemap(width=width,height=width,\
            resolution='c',projection='aeqd',\
            lat_0=lat_0,lon_0=lon_0)
# draw coasts and fill continents.
m.drawcoastlines(linewidth=0.5)
m.fillcontinents()
# 20 degree graticule.
m.drawparallels(arange(-80,81,20))
m.drawmeridians(arange(-180,180,20))
# draw a red dot at the center.
xpt, ypt = m(lon_0, lat_0)
m.plot([xpt],[ypt],'ro') 
# draw the title.
title('The World According to Garp in '+location)
show()
예제 #8
0
            projection = 'sp' + proj
        elif hem == 'North':
            projection = 'np' + proj
        # setup map projection
        # centered on Australia (for SH) or US (for NH).
        if proj == 'ortho':
            m = Basemap(projection='ortho',
                        resolution='c',
                        area_thresh=10000.,
                        lat_0=lat_0,
                        lon_0=lon_0_ortho)
        else:
            m = Basemap(boundinglat=bounding_lat,lon_0=lon_0,\
                        resolution='c',area_thresh=10000.,projection=projection)
        # compute native map projection coordinates for lat/lon grid.
        x, y = m(*meshgrid(lons, lats))
        ax = fig.add_subplot(2, 2, npanel)
        # make filled contour plot.
        cs = m.contourf(x, y, etopo, 20, cmap=cm.jet)
        # draw coastlines.
        m.drawcoastlines()
        # draw parallels and meridians.
        m.drawparallels(arange(-80., 90, 20.))
        m.drawmeridians(arange(0., 360., 60.))
        # draw boundary around map region.
        m.drawmapboundary()
        # draw title.
        title(hem + ' Polar ' + projname, y=1.05, fontsize=12)
    show()
    #savefig('polarmap'+hem+'.eps')
예제 #9
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; nlons = 145; delta = 2.*p.pi/(nlons-1)
lats = (0.5*p.pi-delta*p.indices((nlats,nlons))[0,:,:])
lons = (delta*p.indices((nlats,nlons))[1,:,:])
예제 #10
0
# read shapefile.
shp_info = m.readshapefile('huralll020','hurrtracks',drawbounds=False)
print shp_info
# find names of storms that reached Cat 4.
names = []
for shapedict in m.hurrtracks_info:
    cat = shapedict['CATEGORY']
    name = shapedict['NAME']
    if cat in ['H4','H5'] and name not in names:
        if name != 'NOT NAMED':  names.append(name)
print names
print len(names)
# plot tracks of those storms.
for shapedict,shape in zip(m.hurrtracks_info,m.hurrtracks):
    name = shapedict['NAME']
    cat = shapedict['CATEGORY']
    if name in names:
        xx,yy = zip(*shape)
        # show part of track where storm > Cat 4 as thick red.
        if cat in ['H4','H5']: 
            p.plot(xx,yy,linewidth=1.5,color='r')
        elif cat in ['H1','H2','H3']:
            p.plot(xx,yy,color='k')
# draw coastlines, meridians and parallels.
m.drawcoastlines()
m.drawcountries()
m.drawparallels(p.arange(10,70,20),labels=[0,1,0,0])
m.drawmeridians(p.arange(-100,0,20),labels=[0,0,0,1])
p.title('Atlantic Hurricane Tracks (Storms Reaching Category 4)')
p.show()
예제 #11
0
# 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')
title('Great Circle from New York to London')
show()
예제 #12
0
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
ax.set_yticks([])
title('Cylindrical Equidistant')
print 'plotting Cylindrical Equidistant example, close plot window to proceed ...'
show()

m = Basemap(lons[0],-80.,lons[-1],80.,\
            resolution='c',area_thresh=10000.,projection='merc',\
            lon_0=0.5*(lons[0]+lons[-1]),lat_ts=20.)
# define grid (nx x ny regularly spaced native projection grid)
nx = len(lons)
ny = int(80. * len(lats) / 90.)
lonsout, latsout = m.makegrid(nx, ny)
topodat = interp(topoin, lons, lats, lonsout, latsout)
xsize = rcParams['figure.figsize'][0]
예제 #13
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()
예제 #14
0
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'
# values outside of projection limb will be masked.
for k in range(4):
예제 #15
0
    ax = gca()
    l,b,w,h = ax.get_position()
    b = 0.5 - 0.5*w*m.aspect; h = w*m.aspect
    #l = 0.5 - 0.5*h/m.aspect; w = h/m.aspect
    ax.set_position([l,b,w,h])
    corners = ((m.xmin,m.ymin), (m.xmax,m.ymax))
    ax.update_datalim( corners )                                          
    axis([m.xmin, m.xmax, m.ymin, m.ymax])  
    
    # draw map.
    if plot in ['pcolor','imshow']:                                         
        m.drawcoastlines(ax)
    else:
        m.fillcontinents(ax,color='gray')
	
    # draw parallels
    delat = 30.
    delon = 90.
    circles = arange(10.,90.+delat,delat).tolist()
    m.drawparallels(ax,circles,labels=[0,0,1,1])

    # draw meridians
    meridians = arange(0.,360.,delon)
    m.drawmeridians(ax,meridians,labels=[1,1,1,1],fontsize=10)

    ax.set_xticks([]) # no ticks
    ax.set_yticks([])
    title('500 hPa Height - '+plot,y=1.075)

show()
예제 #16
0
        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
    # TODO: we must do something nicer!!
    import vcs, EzTemplate
    x = vcs.init()
    T = EzTemplate.Multi(rows=nrow,
                         columns=ncol)  # Nrow added 1 for original data row
예제 #17
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()

예제 #18
0
            resolution='c',area_thresh=10000.,projection='lcc',\
            lat_1=50.,lon_0=-107.)
# transform to nx x ny regularly spaced native projection grid
nx = int((m.xmax-m.xmin)/40000.)+1; ny = int((m.ymax-m.ymin)/40000.)+1
topodat = m.transform_scalar(topoin,lons,lats,nx,ny)
# set up 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 image over map.
im = m.imshow(topodat,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
m.drawcoastlines()
m.drawcountries()
m.drawstates()
#m.fillcontinents()
# draw parallels
delat = 20.
parallels = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(parallels,labels=[1,1,0,1]) # labels on left, right, bottom.
# draw meridians
delon = 30.
meridians = arange(10.,360.,delon)
m.drawmeridians(meridians,labels=[1,1,0,1]) # labels on left, right, bottom.

title('ETOPO Topography - Lambert Conformal Conic')
show()
예제 #19
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
예제 #20
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()
예제 #21
0
# Lambert Conformal map of lower 48 states.
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
            projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
fig=p.figure(figsize=(8,m.aspect*8))
fig.add_axes([0.1,0.1,0.8,0.8])
# draw climate division boundaries.
shp_info = m.readshapefile('divisions','climdivs',drawbounds=True)
print shp_info
# make sure the shapefile has polygons (and not just lines).
if shp_info[1] != 5:
    print 'warning: shapefile does not contain polygons'
# choose a color for each climate division (randomly).
colors={}
divnames=[]
print m.climdivs_info[0].keys()
for shapedict in m.climdivs_info:
    divname = shapedict['ST']+repr(shapedict['DIV'])
    colors[divname] = (random.uniform(0,1),random.uniform(0,1),random.uniform(0,1))
    divnames.append(divname)
# cycle through climate divnames, color each one.
for nshape,seg in enumerate(m.climdivs):
    xx,yy = zip(*seg)
    color = rgb2hex(colors[divnames[nshape]]) 
    p.fill(xx,yy,color,edgecolor=color)
# draw meridians and parallels.
m.drawparallels(nx.arange(25,65,20),labels=[1,0,0,0])
m.drawmeridians(nx.arange(-120,-40,20),labels=[0,0,0,1])
p.title('NCDC Climate Divisions')
p.show()
예제 #22
0
from matplotlib.toolkits.basemap import Basemap
import cPickle
from pylab import *
# 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 Basemap instance (global cylindrical equidistant is default)
m = Basemap(lons[0], lats[0], lons[-1], lats[-1])
# create figure with same aspect ratio as map.
xsize = rcParams['figure.figsize'][0]
fig = figure(figsize=(xsize, m.aspect * xsize))
fig.add_axes([0.1, 0.1, 0.8, 0.8])
im = m.imshow(etopo)
# draw coastlines and fill continents.
m.drawcoastlines()
m.fillcontinents()
# draw parallels, label on bottom.
circles = arange(-90., 120., 30.)
m.drawparallels(circles, labels=[1, 0, 0, 0])
# draw meridians, label on left.
meridians = arange(0., 390., 60.)
m.drawmeridians(meridians, labels=[0, 0, 0, 1])
title('Cylindrical Equidistant')
show()
예제 #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 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
예제 #24
0
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('>3$\sigma$ detections composite map: skewness')
title('>3$\sigma$ detections composite map: kurtosis')
colorbar();

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

# north polar projection.
m2 = Basemap(llcrnrlon=-45.,llcrnrlat=10.,urcrnrlon=135.,urcrnrlat=10., projection='stere', lat_0=90.,lon_0=0.,lat_ts=90.)
#            resolution='c',area_thresh=10000.,

fig2 = m2.createfigure()
x, y = m2(lons, lats)
cs = m2.contourf(x,y,map,color_num,cmap=cm.jet)
예제 #25
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")
예제 #26
0
    def draw_clustered_strain_location(self,
                                       label_ls,
                                       weighted_pos_ls,
                                       diameter_ls,
                                       label_type,
                                       label_type2label_name,
                                       pic_area=[-180, -90, 180, 90],
                                       output_fname_prefix=None,
                                       label_name=None):
        """
		2007-07-11
		draw populations derived from connected_components of the strain network
		#each pie denotes a population, with diameter proportional to the size of the population
		#each pie labeled with the number of strains in that population
		2007-07-13
			use popid as label
		2007-07-17
			no parallels, no meridians
		2007-08-29
			copied from CreatePopulation.py
		2007-09-11
			add label name
		2007-10-14
			correct a bug in 5*diameter_ls. diameter_ls has to an array

		"""
        sys.stderr.write("Drawing population map...")
        import pylab
        from matplotlib.toolkits.basemap import Basemap
        pylab.clf()
        fig = pylab.figure()
        fig.add_axes([0.05, 0.05, 0.9, 0.9])  #[left, bottom, width, height]
        m = Basemap(llcrnrlon=pic_area[0],llcrnrlat=pic_area[1],urcrnrlon=pic_area[2],urcrnrlat=pic_area[3],\
        resolution='l',projection='mill')

        euc_coord1_ls = []
        euc_coord2_ls = []
        ax = pylab.gca()
        for i in range(len(weighted_pos_ls)):
            lat, lon = weighted_pos_ls[i]
            euc_coord1, euc_coord2 = m(lon,
                                       lat)  #longitude first, latitude 2nd
            euc_coord1_ls.append(euc_coord1)
            euc_coord2_ls.append(euc_coord2)
            ax.text(euc_coord1,
                    euc_coord2,
                    str(label_ls[i]),
                    size=5,
                    alpha=0.5,
                    horizontalalignment='center',
                    verticalalignment='center',
                    zorder=12)
        import numpy
        diameter_ls = numpy.array(diameter_ls)
        m.scatter(euc_coord1_ls,
                  euc_coord2_ls,
                  5 * diameter_ls,
                  marker='o',
                  color='r',
                  alpha=0.3,
                  zorder=10,
                  faceted=False)

        #m.drawcoastlines()
        m.drawparallels(pylab.arange(-90, 90, 30), labels=[
            1, 1, 0, 1
        ])  #labels intersect the left, right, top bottom of the plot
        m.drawmeridians(pylab.arange(-180, 180, 30), labels=[1, 1, 0, 1])
        m.fillcontinents()
        m.drawcountries()
        m.drawstates()
        pylab.title("worldwide distribution of %s populations, labeled by %s" %
                    (len(weighted_pos_ls), label_type2label_name[label_type]))
        if output_fname_prefix:
            pylab.savefig('%s_pop_map.eps' % output_fname_prefix, dpi=300)
            pylab.savefig('%s_pop_map.svg' % output_fname_prefix, dpi=300)
            pylab.savefig('%s_pop_map.png' % output_fname_prefix, dpi=300)
        del m, pylab, Basemap
        sys.stderr.write("Done.\n")
예제 #27
0
cax = axes([0.875, 0.1, 0.05, 0.75]) # setup colorbar axes.
colorbar(tickfmt='%d', cax=cax) # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
#m.drawcountries()
#m.drawstates()
#m.fillcontinents()
# draw parallels
delat = 30.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles,labels=[1,0,0,1])
# draw meridians
delon = 60.
meridians = arange(-180,180,delon)
m.drawmeridians(meridians,labels=[1,0,0,1])
title('Cylindrical Equidistant')
print 'plotting Cylindrical Equidistant example, close plot window to proceed ...'
show()

# setup miller cylindrical map projection.
m = Basemap(-180.,-90.,180.,90.,\
            resolution='c',area_thresh=10000.,projection='mill')
# transform to nx x ny regularly spaced native projection grid
nx = len(lons); ny = len(lats)
topodat = m.transform_scalar(topoin,lons,lats,nx,ny)
# setup figure with same aspect ratio as map.
xsize = rcParams['figure.figsize'][0]
fig=figure(figsize=(xsize,m.aspect*xsize))
fig.add_axes([0.1,0.1,0.75,0.75])
# plot image over map.
예제 #28
0
lon[-1] = tmp[0] + 360
del tmp

f.close()

#--- 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,
예제 #29
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
예제 #30
0
m = Basemap(-135.,-20.,45.,-20.,
             resolution='c',area_thresh=10000.,projection='laea',
             lat_0=90.,lon_0=-90.)

cmap = cm.jet
fig = figure(figsize=(6,6))

ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

x,y = m(lons, lats)
cs = contour(x,y,hgt,15,linewidths=0.5,colors='k')
cs = contourf(x,y,hgt,15,cmap=cmap,colors=None)

# 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], fontsize=16)

# draw meridians
meridians = arange(0.,360.,delon)
m.drawmeridians(meridians,labels=[1,1,1,1],fontsize=16)


savefig('contour_small.png', dpi=50)
savefig('contour_large', dpi=120)
show()
예제 #31
0
print shp_info
# find names of storms that reached Cat 4.
names = []
for shapedict in m.hurrtracks_info:
    cat = shapedict['CATEGORY']
    name = shapedict['NAME']
    if cat in ['H4', 'H5'] and name not in names:
        # only use named storms.
        if name != 'NOT NAMED': names.append(name)
print names
print len(names)
# plot tracks of those storms.
for shapedict, shape in zip(m.hurrtracks_info, m.hurrtracks):
    name = shapedict['NAME']
    cat = shapedict['CATEGORY']
    if name in names:
        xx, yy = zip(*shape)
        # show part of track where storm > Cat 4 as thick red.
        if cat in ['H4', 'H5']:
            p.plot(xx, yy, linewidth=1.5, color='r')
        elif cat in ['H1', 'H2', 'H3']:
            p.plot(xx, yy, color='k')
# draw coastlines, meridians and parallels.
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color='#cc9966')
m.drawparallels(p.arange(10, 70, 20), labels=[1, 1, 0, 0])
m.drawmeridians(p.arange(-100, 0, 20), labels=[0, 0, 0, 1])
p.title('Atlantic Hurricane Tracks (Storms Reaching Category 4, 1851-2004)')
p.show()
예제 #32
0
#lons=array(load(lonfile))
#lats=array(load(latfile))
#map,lons = shiftgrid(180,map,lons,start=False)
#subplots_adjust(left=0,right=.99,top=0.99,bottom=0.1,wspace=0,hspace=0)
#m2 = Basemap(projection='moll',lon_0=0.5*(lons[0]+lons[-1]))
#lons, lats = meshgrid(lons, lats)
#levels = arange(-36, 39, 0.2)
#x, y = m2(lons, lats)
#cs = m2.contourf(x,y,map,color_num,cmap=cm.hot)
# EXPERIMENTAL END

if mymeridians == '1':
    m1.drawparallels(arange(-90., 90., DeltaLatitude),
                     labels=[1, 0, 0, 0],
                     fontsize=meridians_fontsize)
    m1.drawmeridians(arange(0., 420., DeltaLongitude), labels=[0, 0, 0, 1])
#   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('>3$\sigma$ detections composite map: skewness')
#title('>3$\sigma$ detections composite map: kurtosis')
#rc('font',c=fgcolor)
#rc('lines', lw=2, c=fgcolor)
if mytitle != 'notitle':
    title(mytitle, color=fgcolor, fontsize=meridians_fontsize)

if mycolorbar == 'moll':
    #    colorbar(tickfmt='%.1lf',)
    #setp(a,pad=0.05)
    #clabel(cs, levels[1::2],  # label every second level
예제 #33
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
    fig.add_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)

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
lon_1 = -120
lon_2 = -140
lat_0 = 47.5
lon_0 = -130
예제 #34
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
예제 #35
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'
예제 #36
0
    def test_drawMap(self):
        sys.stderr.write("Drawing graph on a map ...\n")
        #import pdb
        #pdb.set_trace()
        import StockDB, Stock_250kDB  #StockDB has to be setup otherwise, StockDB.Ecotype.table is None in getEcotypeInfo()
        hostname = 'papaya.usc.edu'
        dbname = 'stock_250k'
        db_user = '******'
        db_passwd = ''
        drivername = 'mysql'
        schema = None
        db = Stock_250kDB.Stock_250kDB(drivername=drivername,
                                       username=db_user,
                                       password=db_passwd,
                                       hostname=hostname,
                                       database=dbname,
                                       schema=schema)
        #doesn't matter which database to connect as far as StockDB is imported
        #db = StockDB.StockDB(drivername=drivername, username=db_user,
        #				password=db_passwd, hostname=hostname, database=dbname, schema=schema)
        db.setup(create_tables=False)
        from common import getEcotypeInfo
        ecotype_info = getEcotypeInfo(db)

        from matplotlib.toolkits.basemap import Basemap
        #from mpl_toolkits.basemap import Basemap
        import pylab
        from matplotlib import rcParams
        rcParams['font.size'] = 6
        rcParams['legend.fontsize'] = 6
        #rcParams['text.fontsize'] = 6	#deprecated. use font.size instead
        rcParams['axes.labelsize'] = 4
        rcParams['axes.titlesize'] = 8
        rcParams['xtick.labelsize'] = 4
        rcParams['ytick.labelsize'] = 4

        pylab.clf()

        #fig = pylab.figure()
        #fig.add_axes([0.05,0.05,0.9,0.9])	#[left, bottom, width, height]
        axe_map = pylab.axes([0.5, 0.02, 0.4, 0.8], frameon=False)
        axe_map.set_title("Global Arabidopsis Ecotype Distribution")
        axe_map.set_xlabel('ecotype is drawn as circles.')
        axe_map.set_ylabel('strains')
        pic_area = [-140, -40, 140, 70]
        m = Basemap(llcrnrlon=pic_area[0],llcrnrlat=pic_area[1],urcrnrlon=pic_area[2],urcrnrlat=pic_area[3],\
        resolution='l',projection='mill', ax=axe_map)
        """
		llcrnrx = -self.rmajor
		llcrnry = -self.rmajor
		urcrnrx = -llcrnrx
		urcrnry = -llcrnry
		"""
        #m.drawcoastlines()
        #m.bluemarble()
        m.drawparallels(pylab.arange(-90, 90, 30),
                        labels=[1, 1, 0, 1],
                        size=4,
                        linewidth=0.1)
        m.drawmeridians(pylab.arange(-180, 180, 30),
                        labels=[1, 1, 0, 1],
                        size=4,
                        linewidth=0.1)
        m.fillcontinents()
        m.drawcountries(linewidth=0.1)
        #m.drawstates()
        #m.drawlsmask((0,255,0,255), (0,0,255,255), lakes=True)
        #m.drawlsmask('coral','aqua',lakes=True)

        print "xlim:", axe_map.get_xlim()
        print "ylim:", axe_map.get_ylim()

        xlim = axe_map.get_xlim()
        ylim = axe_map.get_ylim()
        """
		for strain_id in StrainID2PCAPosInfo.strain_id_ls:
			img_y_pos = StrainID2PCAPosInfo.strain_id2img_y_pos[strain_id]
			phenotype_row_index = phenData.row_id2row_index[strain_id]
			phenotype = phenData.data_matrix[phenotype_row_index][phenotype_col_index]
			ecotype_id = int(strain_id)
			ecotype_obj = ecotype_info.ecotype_id2ecotype_obj.get(ecotype_id)
			if ecotype_obj:
				lat, lon = ecotype_obj.latitude, ecotype_obj.longitude
			else:
				sys.stderr.write("Warning: Ecotype %s not in ecotype_info (fetched from stock db).\n"%ecotype_id)
				continue
			if lat and lon:
				x, y = m(lon, lat)
				color = cmap(norm(phenotype))
				ax.plot([0, x], [img_y_pos, y], linestyle='--', alpha=0.2, linewidth=0.2)
				ax.scatter([x],[y], s=10, linewidth=0, facecolor=color)	#, zorder=10)
		"""

        #pylab.title("Global Arabidopsis Ecotype Distribution")
        output_fname_prefix = '/tmp/map'

        print "ylim:", axe_map.get_ylim()
        axe_map.set_xlim(xlim)
        axe_map.set_ylim(ylim)

        axe_chromosome = pylab.axes([0.05, 0.02, 0.8, 0.8], frameon=False)
        axe_chromosome.set_title("chromosome")

        #fix the two transformations before doing cross-axe drawings
        axe_map.transData.freeze()  # eval the lazy objects
        axe_map.transAxes.freeze()
        axe_chromosome.transData.freeze()  # eval the lazy objects
        axe_chromosome.transAxes.freeze()
        no_of_ecotypes = 200
        ecotype_id_ls = ecotype_info.ecotype_id2ecotype_obj.keys(
        )[:no_of_ecotypes]
        no_of_ecotypes_drawn = 0
        for i in range(no_of_ecotypes):
            ecotype_id = ecotype_id_ls[i]
            y_pos = i / float(no_of_ecotypes)
            #y_pos = i/float(no_of_ecotypes)*ylim[1]
            ecotype_obj = ecotype_info.ecotype_id2ecotype_obj.get(ecotype_id)
            if ecotype_obj:
                lat, lon = ecotype_obj.latitude, ecotype_obj.longitude
            else:
                sys.stderr.write(
                    "Warning: Ecotype %s not in ecotype_info (fetched from stock db).\n"
                    % ecotype_id)
                continue
            if lat and lon:
                x, y = m(lon, lat)
                #axe_map.plot([0, x], [y_pos, y], linestyle='--', alpha=0.2, linewidth=0.2)
                axe_map.set_xlim(xlim)
                axe_map.set_ylim(ylim)
                axe_map.scatter([x], [y],
                                s=5,
                                linewidth=0,
                                facecolor='r',
                                alpha=0.2,
                                zorder=10)
                canvas_x, canvas_y = axe_map.transData.xy_tup((x, y))
                axe_chromosome_xy = axe_chromosome.transData.inverse_xy_tup(
                    (canvas_x, canvas_y))
                axe_chromosome.plot([0, axe_chromosome_xy[0]],
                                    [y_pos, axe_chromosome_xy[1]],
                                    linestyle='--',
                                    alpha=0.2,
                                    linewidth=0.2)
                no_of_ecotypes_drawn += 1
        #release two transformations
        axe_map.transData.thaw()  # eval the lazy objects
        axe_map.transAxes.thaw()
        axe_chromosome.transData.thaw()  # eval the lazy objects
        axe_chromosome.transAxes.thaw()
        #set to the same x/y_lim before cross-axe drawing
        axe_map.set_xlim(xlim)
        axe_map.set_ylim(ylim)
        axe_chromosome.set_xlim([0, 1])
        axe_chromosome.set_ylim([0, 1])
        if output_fname_prefix:
            pylab.savefig('%s.png' % output_fname_prefix, dpi=600)
            pylab.savefig('%s.svg' % output_fname_prefix)
        sys.stderr.write("%s ecotypes drawn. Done.\n" % (no_of_ecotypes_drawn))
예제 #37
0
# in which direction to depart for other points on earth and how far
# it will be to reach that destination.
# The specified point shows up as a red dot in the center of the map.

# This example shows how to use the width and height keywords
# to specify the map projection region (instead of specifying
# the lat/lon of the upper right and lower left corners).

# user enters the lon/lat of the point, and it's name
lon_0 = float(raw_input('input reference lon (degrees):'))
lat_0 = float(raw_input('input reference lat (degrees):'))
location = raw_input('name of location:')

# use these values to setup Basemap instance.
width = 28000000
m = Basemap(width=width,height=width,\
            resolution='c',projection='aeqd',\
            lat_0=lat_0,lon_0=lon_0)
# draw coasts and fill continents.
m.drawcoastlines(linewidth=0.5)
m.fillcontinents()
# 20 degree graticule.
m.drawparallels(arange(-80, 81, 20))
m.drawmeridians(arange(-180, 180, 20))
# draw a red dot at the center.
xpt, ypt = m(lon_0, lat_0)
m.plot([xpt], [ypt], 'ro')
# draw the title.
title('The World According to Garp in ' + location)
show()
예제 #38
0
            lat_1=33,
            lat_2=45,
            lon_0=-95)
fig = p.figure(figsize=(8, m.aspect * 8))
fig.add_axes([0.1, 0.1, 0.8, 0.8])
# draw climate division boundaries.
shp_info = m.readshapefile('divisions', 'climdivs', drawbounds=True)
print shp_info
# make sure the shapefile has polygons (and not just lines).
if shp_info[1] != 5:
    print 'warning: shapefile does not contain polygons'
# choose a color for each climate division (randomly).
colors = {}
divnames = []
print m.climdivs_info[0].keys()
for shapedict in m.climdivs_info:
    divname = shapedict['ST'] + repr(shapedict['DIV'])
    colors[divname] = (random.uniform(0, 1), random.uniform(0, 1),
                       random.uniform(0, 1))
    divnames.append(divname)
# cycle through climate divnames, color each one.
for nshape, seg in enumerate(m.climdivs):
    xx, yy = zip(*seg)
    color = rgb2hex(colors[divnames[nshape]])
    p.fill(xx, yy, color, edgecolor=color)
# draw meridians and parallels.
m.drawparallels(nx.arange(25, 65, 20), labels=[1, 0, 0, 0])
m.drawmeridians(nx.arange(-120, -40, 20), labels=[0, 0, 0, 1])
p.title('NCDC Climate Divisions')
p.show()
예제 #39
0
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.
ax.apply_aspect()
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=MultipleLocator(320))  # draw colorbar
P.axes(ax)  # make the original axes current again
msh.drawcoastlines(linewidth=0.5)
예제 #40
0
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)
# reset figure size to have same aspect ratio as map.
# fig will be 8 inches wide.
# (don't use createfigure, since that imports pylab).
fig.set_figsize_inches((8,m.aspect*8.))
# 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.
cax = fig.add_axes([0.125, 0.05, 0.75, 0.05],frameon=False)
fig.colorbar(cs, cax=cax, tickfmt='%d', orientation='horizontal',clabels=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'
예제 #41
0
urcrnrlon = llcrnrlon+(array.shape[1]-1)*coords[1]
urcrnrlat = coords[3]
llcrnrlat = urcrnrlat+(array.shape[0]-1)*coords[5]
# create Basemap instance.
m = Basemap(llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat,urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat,projection='cyl')
# create a figure, add an axes
# (leaving room for a colorbar).
fig = p.figure()
ax = fig.add_axes([0.1,0.1,0.75,0.75])
# plot image from DEM over map.
im = m.imshow(array,origin='upper')
# make a colorbar.
cax = p.axes([0.875, 0.1, 0.05, 0.75]) # setup colorbar axes.
p.colorbar(cax=cax) # draw colorbar
p.axes(ax)  # make the original axes current again
# draw meridians and parallels.
m.drawmeridians(p.linspace(llcrnrlon+0.1,urcrnrlon-0.1,5),labels=[0,0,0,1],fmt='%4.2f')
m.drawparallels(p.linspace(llcrnrlat+0.1,urcrnrlat-0.1,5),labels=[1,0,0,0],fmt='%4.2f')
# plot county boundaries from
# http://edcftp.cr.usgs.gov/pub/data/nationalatlas/countyp020.tar.gz
shp_info = m.readshapefile('countyp020','counties',drawbounds=True,linewidth=1.0)
# plot some cities.
lons = [-105.22,-105.513,-105.316,-105.47]; lats = [39.76,39.801,39.633,39.41]
names =  ['Golden','Central City','Evergreen','Bailey']
x,y = m(lons,lats)
m.plot(x,y,'ko')
for name,xx,yy in zip(names,x,y):
    p.text(xx+0.01,yy+0.01,name)
p.title(gd.GetDescription()+' USGS DEM with county boundaries')
p.show()
예제 #42
0
from matplotlib.toolkits.basemap import Basemap
from pylab import title, show, arange
# create Basemap instance for Geostationary (satellite view) projection.
lon_0 = float(raw_input('enter reference longitude (lon_0):'))
h = float(raw_input('enter satellite height above equator in meters (satellite_height):'))
m = Basemap(projection='geos',lon_0=lon_0,satellite_height=h,rsphere=(6378137.00,6356752.3142),)
# plot land-sea mask.
rgba_land = (0,255,0,255) # land green.
rgba_ocean = (0,0,255,255) # ocean blue.
# lakes=True means plot inland lakes with ocean color.
m.drawlsmask(rgba_land, rgba_ocean, lakes=True)
# draw parallels and meridians.
m.drawparallels(arange(-90.,120.,30.))
m.drawmeridians(arange(0.,420.,60.))
m.drawmapboundary()
title('Geostationary Map Centered on Lon=%s, Satellite Height=%s' % (lon_0,h))
show()
예제 #43
0
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.drawcountries(ax)
m.drawstates(ax)
m.fillcontinents(ax)
# draw parallels
delat = 30.
circles = arange(0.,90.,delat).tolist()+\
          arange(-delat,-90,-delat).tolist()
m.drawparallels(ax,circles)
# convert parallels to native map projection coordinates
nativeCoordCircles = m([0]*len(circles), circles)[1]
ax.set_yticks(nativeCoordCircles)
ax.yaxis.set_major_formatter(MercYAxisFormatter(m))
# draw meridians
delon = 60.
lon1 = int(m.llcrnrlon/delon)*delon
lon2 = (int(m.urcrnrlon/delon)+1)*delon
meridians = arange(lon1,lon2,delon)
m.drawmeridians(ax,meridians)
ax.set_xticks(meridians)
title('Mercator with Longitude and Latitude Labels')
print 'plotting Mercator Y-axis latitude ticks example, close plot window to proceed ...'
show()
예제 #44
0
 #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
 else:
    p.savefig('anim%03i'%nframe+'.png')
예제 #45
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")
예제 #46
0
from matplotlib.toolkits.basemap import Basemap
import cPickle
from pylab import *
# 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 Basemap instance (global cylindrical equidistant is default)
m = Basemap(lons[0],lats[0],lons[-1],lats[-1])
# create figure with same aspect ratio as map.
xsize = rcParams['figure.figsize'][0]
fig=figure(figsize=(xsize,m.aspect*xsize))
fig.add_axes([0.1,0.1,0.8,0.8])
im = m.imshow(etopo)
# draw coastlines and fill continents.
m.drawcoastlines()
m.fillcontinents()
# draw parallels, label on bottom.
circles = arange(-90.,120.,30.)
m.drawparallels(circles,labels=[1,0,0,0])
# draw meridians, label on left.
meridians = arange(0.,390.,60.)
m.drawmeridians(meridians,labels=[0,0,0,1])
title('Cylindrical Equidistant')
show()

예제 #47
0
cax = axes([0.875, 0.1, 0.05, 0.75])  # setup colorbar axes.
colorbar(tickfmt='%d', cax=cax)  # draw colorbar
axes(ax)  # make the original axes current again
m.drawcoastlines()
#m.drawcountries()
#m.drawstates()
#m.fillcontinents()
# draw parallels
delat = 30.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(circles, labels=[1, 0, 0, 1])
# draw meridians
delon = 60.
meridians = arange(-180, 180, delon)
m.drawmeridians(meridians, labels=[1, 0, 0, 1])
title('Cylindrical Equidistant')
print 'plotting Cylindrical Equidistant example, close plot window to proceed ...'
show()

# setup miller cylindrical map projection.
m = Basemap(-180.,-90.,180.,90.,\
            resolution='c',area_thresh=10000.,projection='mill')
# transform to nx x ny regularly spaced native projection grid
nx = len(lons)
ny = len(lats)
topodat = m.transform_scalar(topoin, lons, lats, nx, ny)
# setup figure with same aspect ratio as map.
xsize = rcParams['figure.figsize'][0]
fig = figure(figsize=(xsize, m.aspect * xsize))
fig.add_axes([0.1, 0.1, 0.75, 0.75])
예제 #48
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()
예제 #49
0
# transform lons and lats to map coordinates.
x,y = m(array(lons_out)/d2r, array(lats_out)/d2r)
# find just those points in map region.
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()
예제 #50
0
	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
	# TODO: we must do something nicer!!
	import vcs,EzTemplate
	x=vcs.init()
	T=EzTemplate.Multi(rows=nrow,columns=ncol) # Nrow added 1 for original data row
	mn,mx=-1,1
	levels = vcs.mkscale(mn,mx)
	levels.insert(0,-1.e20) # extension left side
예제 #51
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
예제 #52
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()
bm_ps.drawparallels(parallels, labels = [1,1,0,0])
bm_ps.drawmeridians(meridians, labels = [0,0,1,1])
예제 #53
0
def add_text(rlon, rlat, txt, m=None, **keywords):
    show_lat = 1
    if ('show_lat' in keywords):
        show_lat = keywords['show_lat']
    rlon = array(rlon)
    rlat = array(rlat)

    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])
    x, y = m(rlon, rlat)
    for i in range(size(rlon)):
        text(x[i], y[i], txt[i], fontsize=10)

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

    return m
예제 #54
0
# 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')
title('Great Circle from New York to London')
show()
예제 #55
0
# 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)
# interpolate rgba values from proj='cyl' (geographic coords) to 'lcc'
# values outside of projection limb will be masked.
예제 #56
0
nx = int((m.xmax - m.xmin) / 40000.) + 1
ny = int((m.ymax - m.ymin) / 40000.) + 1
topodat = m.transform_scalar(topoin, lons, lats, nx, ny)
# set up 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 image over map.
im = m.imshow(topodat, 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
m.drawcoastlines()
m.drawcountries()
m.drawstates()
#m.fillcontinents()
# draw parallels
delat = 20.
parallels = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
m.drawparallels(parallels, labels=[1, 1, 0,
                                   1])  # labels on left, right, bottom.
# draw meridians
delon = 30.
meridians = arange(10., 360., delon)
m.drawmeridians(meridians, labels=[1, 1, 0,
                                   1])  # labels on left, right, bottom.

title('ETOPO Topography - Lambert Conformal Conic')
show()
예제 #57
0
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'
예제 #58
0
파일: view.py 프로젝트: jwblin/qtcm
lon = p.zeros((p.size(tmp)+1,))
lon[0:-1] = tmp[:]
lon[-1] = tmp[0]+360
del tmp

f.close()


#--- 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'