def draw_client_density():

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

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

    canvas.print_figure(outdir+'/clientmap.png', dpi=100)
예제 #2
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")
예제 #3
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")
예제 #4
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")
예제 #5
0
파일: hires.py 프로젝트: jtomase/matplotlib
import time

# create new figure
fig = figure()
# create Basemap instance. Use 'high' resolution coastlines.
t1 = time.clock()
m = Basemap(llcrnrlon=-11.,
            llcrnrlat=49.,
            urcrnrlon=5.,
            urcrnrlat=59.,
            resolution='h',
            projection='tmerc',
            lon_0=-8.,
            lat_0=0.)
print 'time to create instance with high-res boundaries = ', time.clock() - t1
# draw coastlines and fill continents.
m.drawcoastlines()
m.fillcontinents()
# draw political boundaries.
m.drawcountries(linewidth=1)
# draw major rivers.
m.drawrivers(color='b')
# draw parallels
circles = arange(48, 65, 2).tolist()
m.drawparallels(circles, labels=[1, 1, 0, 0])
# draw meridians
meridians = arange(-12, 13, 2)
m.drawmeridians(meridians, labels=[0, 0, 1, 1])
title("High-Res British Isles", y=1.075)
show()
예제 #6
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()
map.drawcountries()
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,34.00,38.55,48.25,17.29]
lons=[-105.16,-119.40,-77.00,-114.21,-88.10]
cities=['Boulder, CO','Santa Cruz, 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)
# 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,:,:])
예제 #7
0
# 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, x, y = m.transform_scalar(topoin, lons, lats, nx, ny, returnxy=True)
# 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 with imshow.
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
# plot blue dot on boulder, colorado and label it as such.
xpt, ypt = m(-104.237, 40.125)
m.plot([xpt], [ypt], 'bo')
text(xpt + 100000, ypt + 100000, 'Boulder')
# draw coastlines and political boundaries.
m.drawcoastlines()
m.drawcountries()
m.drawstates()
# draw parallels and meridians.
# label on left, right and bottom of map.
parallels = arange(0., 80, 20.)
m.drawparallels(parallels, labels=[1, 1, 0, 1])
meridians = arange(10., 360., 30.)
m.drawmeridians(meridians, labels=[1, 1, 0, 1])

title('ETOPO Topography - Lambert Conformal Conic')
show()
예제 #8
0
            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]
fig = figure(figsize=(xsize, m.aspect * xsize))
fig.add_axes([0.1, 0.1, 0.75, 0.75])
im = imshow(topodat,
            cm.jet,
            extent=(m.llcrnrx, m.urcrnrx, m.llcrnry, m.urcrnry),
            origin='lower')
ax = gca()  # get current axis instance
m.drawcoastlines(ax)
m.drawcountries(ax)
m.drawstates(ax)
m.fillcontinents(ax)
# draw parallels
m.drawparallels(ax, circles, labels=[1, 1, 1, 1])
# draw meridians
m.drawmeridians(ax, meridians, labels=[1, 1, 1, 1])
ax.set_xticks([])  # no ticks
ax.set_yticks([])
title('Mercator', y=1.1)
print 'plotting Mercator example, close plot window to proceed ...'
show()

m = Basemap(-145.5,1.,-2.566,46.352,\
            resolution='c',area_thresh=10000.,projection='lcc',\
            lat_1=50.,lon_0=-107.)
예제 #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
예제 #10
0
파일: setwh.py 프로젝트: jtomase/matplotlib
          arange(-delat,-90.-delat,-delat).tolist()
delon = 30.
meridians = arange(10., 360., delon)
npanel = 0
# plots of the US.
projs = ['lcc', 'aeqd', 'aea', 'laea', 'eqdc', 'stere']
fig = figure(figsize=(8, 12))
for proj in projs:
    m = Basemap(width=width,height=height,
                resolution='c',projection=proj,\
                lat_0=lat_0,lon_0=lon_0)
    npanel = npanel + 1
    subplot(3, 2, npanel)
    # setup figure with same aspect ratio as map.
    m.drawcoastlines()
    m.drawcountries()
    m.fillcontinents()
    m.drawstates()
    m.drawparallels(circles)
    m.drawmeridians(meridians)
    title('proj = ' + proj + ' centered on %sW, %sN' % (lon_0, lat_0),
          fontsize=10)
show()

proj = 'omerc'
delat = 10.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
delon = 10.
meridians = arange(10., 360., delon)
lat_1 = 40
예제 #11
0
      """
      lon, lat = self.baseMap(0.0, y, inverse=True)
      return "%g" % lat

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

proj = 'omerc'
delat = 10.
circles = arange(0.,90.+delat,delat).tolist()+\
          arange(-delat,-90.-delat,-delat).tolist()
delon = 10.
meridians = arange(10.,360.,delon)
lat_1 = 40; lat_2 = 55
lon_1 = -120; lon_2 = -140
예제 #15
0
ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
# create Basemap instance for a Geostationary projection.
m = Basemap(projection='geos',
            lon_0=lon_0,
            satellite_height=satellite_height,
            resolution='l',
            llcrnrlon=ll_lon,
            llcrnrlat=ll_lat,
            urcrnrlon=ur_lon,
            urcrnrlat=ur_lat)
# add data
m.imshow(data, cmap=cm.gray, interpolation='nearest')
clim(0, 255)
# draw coastlines.
m.drawcoastlines(linewidth=0.5, color=overlay_color)
m.drawcountries(linewidth=0.5, color=overlay_color)
# can't label meridians on bottom, because labels would
# be outside map projection region.
m.drawmeridians(arange(10, 76, 5), labels=[0, 0, 1, 0], color=overlay_color)
m.drawparallels(arange(-90, 90, 5), labels=[1, 0, 0, 0], color=overlay_color)
# add a colobar
#colorbar()
# add timestamp and save
fig = gcf()
fig.text(
    x=0.275,
    y=0.025,
    s=
    u'Meteosat-9 VIS 0.6 channel - 12:00 UTC 04/06/2007\n    \N{COPYRIGHT SIGN} EUMETSAT 2007',
    horizontalalignment='left',
    verticalalignment='bottom',
예제 #16
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))
예제 #17
0
x_bm,y_bm = ps2.to_basemap_xy(m2, x_grid / cm_per_m, y_grid / cm_per_m)
#Radius factor used in all of the analyses
R = 4.32

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

##m2.drawstates()
##m2.drawcountries()
##m2.drawcoastlines()
##m2.drawparallels(parallels, labels = [1,1,0,0])
##m2.drawmeridians(meridians, labels = [0,0,1,1])
ob_x, ob_y = ps2.to_basemap_xy(m2, data.x / cm_per_m, data.y / cm_per_m)
#m2.plot(ob_x, ob_y, 'bx')
#m2.plot(x_bm, y_bm, 'g.')
for name in M.cm.cmapnames:
  f = P.figure()
  m2.drawstates()
  m2.drawcountries()
  m2.drawcoastlines()
  m2.drawparallels(parallels, labels = [1,1,0,0])
  m2.drawmeridians(meridians, labels = [0,0,1,1])
  c = m2.contour(x_bm, y_bm, heights_cress, contours, cmap=M.cm.get_cmap(name))
  P.title(name)
  #P.clabel(c)
  P.show()
예제 #18
0
#Do the necessary processing for each analysis
contours = N.arange(5300., 6000., 60.0)
parallels = N.arange(25., 60.0, 10.0)
meridians = N.arange(-120., -60.0, 10.0)
fields = (cress1, cress2, cress3, cress_187, barnes_analyses[0],
  barnes_analyses[1], barnes_analyses[2], barnes_3pass)
names = ('Cressman 1st Pass', 'Cressman 2nd Pass', 'Cressman 3rd Pass',
  'Cressman R=1.87d', r'$\rm{Barnes} \gamma=1.0$',r'$\rm{Barnes} \gamma=0.4$',
  r'$\rm{Barnes} \gamma=0.2$', r'$\rm{Barnes 3-pass} \gamma=1.0$')
filenames = ('cress1', 'cress2', 'cress3', 'cress187', 'barnes1', 'barnes2',
  'barnes3', 'barnes3pass')
for field,name,filename in zip(fields, names, filenames):
  f = P.figure()
  bm_ps.drawstates()
  bm_ps.drawcountries()
  bm_ps.drawcoastlines()
  bm_ps.drawparallels(parallels, labels = [1,1,0,0])
  bm_ps.drawmeridians(meridians, labels = [0,0,1,1])
  cp = bm_ps.contour(x_bm, y_bm, field, contours, cmap=colormap)
  P.clabel(cp, fontsize=fontsize, fmt='%.1f')
  f.text(0.5,0.95,name,horizontalalignment='center',fontsize=16)
  if save_work:
    P.savefig(filename + '.png', dpi = 300)
  else:
    P.show()

filename = 'cress12diff'
f = P.figure()
bm_ps.drawstates()
bm_ps.drawcountries()
예제 #19
0
    def display(self, dirc, **keywords):
        """ display  the data
        keywords: dict which can include the following keywords  minv=0.0, maxv=0.0, dv=0.0,
        show_map=0, map_proj='cyl', show_lat=0, show_lon=0, lat_0=0.0, lon_0=0.0,
        minlat=-90.0, maxlat=90.0, minlon=0.0, maxlon=360.0, use_log=0, level=level
        """

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

        levels = self.grid.get_z()

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

        maxv = 0.0

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

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

        show_map = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            maxlat = 90.0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            title(stitle)
            colorbar()

        show()
        return 0
예제 #20
0
from matplotlib.toolkits.basemap import Basemap
from pylab import *
import time

# create new figure
fig=figure()
# create Basemap instance. Use 'high' resolution coastlines.
t1 = time.clock()
m = Basemap(llcrnrlon=-11.,llcrnrlat=49.,urcrnrlon=5.,urcrnrlat=59.,
            resolution='h',projection='tmerc',lon_0=-8.,lat_0=0.)
print 'time to create instance with high-res boundaries = ',time.clock()-t1
# draw coastlines and fill continents.
m.drawcoastlines()
m.fillcontinents()
# draw political boundaries.
m.drawcountries(linewidth=1)
# draw major rivers.
m.drawrivers(color='b')
# draw parallels
circles = arange(48,65,2).tolist()
m.drawparallels(circles,labels=[1,1,0,0])
# draw meridians
meridians = arange(-12,13,2)
m.drawmeridians(meridians,labels=[0,0,1,1])
title("High-Res British Isles",y=1.075)
show()
예제 #21
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')
# set up figure.
fig = map.createfigure()
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines()
map.drawcountries()
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, 34.00, 38.55, 48.25, 17.29]
lons = [-105.16, -119.40, -77.00, -114.21, -88.10]
cities = [
    'Boulder, CO', 'Santa Cruz, 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)
예제 #22
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()
예제 #23
0
ur_lon = 48.45
ur_lat = 0.2
lon_0 = 0.0
satellite_height = 35785831.0

fig = figure(figsize=(7,7))
ax = fig.add_axes((0.1,0.1,0.8,0.8))
# create Basemap instance for a Geostationary projection.
m = Basemap(projection='geos', lon_0=lon_0, satellite_height=satellite_height,
            resolution='l', llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat)
# add data
m.imshow(data, cmap=cm.gray, interpolation='nearest')
clim(0, 255)
# draw coastlines.
m.drawcoastlines(linewidth=0.5, color=overlay_color)
m.drawcountries(linewidth=0.5, color=overlay_color)
# can't label meridians on bottom, because labels would
# be outside map projection region.
m.drawmeridians(arange(10,76,5), labels=[0,0,1,0], color=overlay_color)
m.drawparallels(arange(-90,90,5), labels=[1,0,0,0], color=overlay_color)
# add a colobar
#colorbar()
# add timestamp and save
fig = gcf()
fig.text(x=0.275, y=0.025, s=u'Meteosat-9 VIS 0.6 channel - 12:00 UTC 04/06/2007\n    \N{COPYRIGHT SIGN} EUMETSAT 2007',
            horizontalalignment='left',
            verticalalignment='bottom',
            fontsize=10,
            fontweight='bold',
            bbox=dict(facecolor='gray', alpha=0.25, pad=15))
fig.set_size_inches((8, 6))