Beispiel #1
0
    def _draw_basemap(self, proj_prop=None, drawparallels=True, vmin_polygons=None, vmax_polygons=None, **kwargs):
        """
        """
        if proj_prop is None:
            raise ValueError(
                'No projection properties are given! Please modify or choose a different backend!')

        the_map = Basemap(ax=self.pax, **proj_prop)
        xm = self.x.timmean()

        Z = xm
        lon = self.x.lon
        lat = self.x.lat

        X, Y = the_map(lon, lat)
        self.im = the_map.pcolormesh(X, Y, Z, **kwargs)

        self.__basemap_ancillary(the_map, drawparallels=drawparallels)

        # add polygons to map
        if self.polygons is not None:
            if False:  # individual polygons
                for p in self.polygons:
                    self._add_single_polygon_basemap(the_map, p)
            else:  # plot all polygons at once
                self._add_polygons_as_collection_basemap(
                    the_map, vmin=vmin_polygons, vmax=vmax_polygons)
Beispiel #2
0
    def mapMake(self,renderdpi,table,msize):
        cn = 0
        start = time()

        #initialize connection to database
        cn = psycopg2.connect(secret.DB_CONNECT)
        cr = cn.cursor()

        #get map ready to go
        fig = plt.figure(figsize=(8,4),dpi = renderdpi)
        fig.add_subplot(1,1,1)
        m = Basemap(projection='merc',llcrnrlat=-60,urcrnrlat=75,\
            llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='i')
        m.drawcoastlines(linewidth=.05)
        m.drawcountries(linewidth=.05)

        photoCnt = 0
        points = []

        cr.execute('SELECT latitude,longitude FROM %s;' %  table)
        for row in cr.fetchall():
            x,y = m(row[1],row[0])#convert to merc projection coords
            points.append((x,y))
            photoCnt += 1
        xs,ys = zip(*points)

        plt.title("%d %s" % (photoCnt,table))
        plt.scatter(xs,ys,s=msize,marker='.',c='green',edgecolors='none')
        plt.savefig(table,dpi = renderdpi)

        print "{:d} {:s}  mapped in {:f} seconds".format(photoCnt,\
                                                         table,time()-start)
def draw_basic_map_of_toronto(axis):
    """Draw a basic map of Toronto.

    :param axis: where to draw the map
    :returns: Basemap with Toronto
    """
    # These are the latitudes of the City of Toronto.
    # (Fiona can be better to find them, e.g., from the 'icitw_wgs84' Shapefile
    #  below.)

    low_left_corner_longitude = -79.75
    low_left_corner_latitude = 43.40
    up_right_corner_longitude = -79.10
    up_right_corner_latitude = 43.95

    to_map = Basemap(
        llcrnrlon=low_left_corner_longitude,
        llcrnrlat=low_left_corner_latitude,
        urcrnrlon=up_right_corner_longitude,
        urcrnrlat=up_right_corner_latitude,
        ellps="WGS84",
        resolution="h",
        area_thresh=0.1,
        ax=axis,
    )

    to_map.drawmapboundary(fill_color="white")
    return to_map
Beispiel #4
0
def basemap_raster_mercator(lon, lat, grid, cmap = None):
  """
  Render a raster in mercator projection.  Locations with no values are
  rendered transparent.
  """
  # longitude/latitude extent
  lons = (np.amin(lon), np.amax(lon))
  lats = (np.amin(lat), np.amax(lat))

  if cmap is None:
    cmap = mpl.cm.jet
    cmap.set_bad('w', 1.0)

  # construct spherical mercator projection for region of interest
  m = Basemap(projection='merc',llcrnrlat=lats[0], urcrnrlat=lats[1],
              llcrnrlon=lons[0],urcrnrlon=lons[1])

  vmin,vmax = np.nanmin(grid),np.nanmax(grid)
  masked_grid = np.ma.array(grid,mask=np.isnan(grid))
  fig = plt.figure(frameon=False)
  plt.axis('off')
  m.pcolormesh(lon,lat,masked_grid,latlon=True,cmap=cmap,vmin=vmin,vmax=vmax)

  str_io = StringIO.StringIO()
  plt.savefig(str_io,bbox_inches='tight',format='png',pad_inches=0,transparent=True)
  bounds = [ (lons[0],lats[0]),(lons[1],lats[0]),(lons[1],lats[1]),(lons[0],lats[1]) ]

  return str_io.getvalue(), bounds
def plot_drainage_areas(path = "data/hydrosheds/test_using_splitting_amno.nc"):
    ds = Dataset(path)
    #basemap = polar_stereographic.basemap
    basemap =  Basemap()
    lons = ds.variables["lon"][:]
    lats = ds.variables["lat"][:]
    channel_slope = ds.variables["slope"][:]

    lons[lons < 0] += 360

    x, y = basemap(lons, lats)




    acc_area = ds.variables["accumulation_area"][:]
    acc_area = np.log(acc_area)
    acc_area = np.ma.masked_where(channel_slope < 0, acc_area)

    basemap.pcolormesh(x, y, acc_area)
    basemap.drawcoastlines()
    plt.colorbar()
    plt.xlim(x.min(), x.max())
    plt.ylim(y.min(), y.max())
    plt.show()
Beispiel #6
0
    def draw_samples(self, n_samples, burnin=100, thin=10):
        if not self.kde_model:
            self.fit_kde()

        # pick starting point
        start_x = np.array([[0., 31.]])

        # get region for restricting samples
        margin = 0.5
        m = Basemap(llcrnrlon=self.uganda_data.LONGITUDE.min() - margin,
            llcrnrlat=self.uganda_data.LATITUDE.min() - margin,
            urcrnrlon=self.uganda_data.LONGITUDE.max() + margin,
            urcrnrlat=self.uganda_data.LATITUDE.max() + margin,
            resolution='l',
            area_thresh=10000)
        m.readshapefile("data/regions/UGA_adm0", "regions", drawbounds=True)
        for xy, info in zip(m.regions, m.regions):
            p = path.Path(xy)

        slice_samples, _ = SliceSampler.SliceSampler.mvslice(self.kde_model.pdf, 
            start_x,
            sample_size=n_samples, 
            burnin=burnin, 
            thin=thin, 
            confirm_region=p)
        
        # we get lat, long; we want x, y
        return np.fliplr(slice_samples)
Beispiel #7
0
    def plot2D_parameter(self,grid,filename):
      
        fig = plt.figure(figsize=(figsize,figsize),dpi=self.cfg.map_dpi)
        
        Lon,Lat = np.meshgrid(self.lon, self.lat)
       
        map = Basemap(llcrnrlon=self.BB['lon'][0],llcrnrlat=self.BB['lat'][0],urcrnrlon=self.BB['lon'][1],urcrnrlat=self.BB['lat'][1],
                      rsphere=(6378137.00,6356752.3142), resolution='l',projection='merc')
    
        x, y = map(Lon, Lat)
        cs2 = map.contourf(x,y,grid,512)
        
        plt.subplots_adjust(left=0.0, right=figsize, top=figsize, bottom=0.0)
        
        self.saveplot(plt,filename)
        plt.close()

        fig1 = plt.figure(figsize=(11,11),dpi=100)
        cb = map.colorbar(cs2,"bottom", size="5%", pad="100%")
        
        name = filename + '_legend.jpg' 
        plt.savefig("maps/"+name, dpi=100,bbox_inches='tight',transparent=False)
        plt.close()
        list_of_maps_to_send.append("maps/"+name)

        img1 = Image.open("maps/"+name)
        w, h = img1.size
        box = (20, h-70, w-10, h-10)
        area = img1.crop(box)
        area.save("maps/"+name,'jpeg')
        plt.close()
def nice_plot(data,xmin,xmax,xint,centerlat,centerlon,stations,color,cmin,
              cmax,levels_t):
    """Make plots in map projection, requires input array, x-min max and 
       interval (also used for y), center of data in lat, lon, station 
       locations, color scale, min and max limits and levels array for color
       scale.
    """
    domain = xmax-xint/2.
    maps = Basemap(projection='laea',lat_0=centerlat,lon_0=centerlon,
                   width=domain*2,height=domain*2)
    s = plt.pcolormesh(np.arange(xmin-xint/2.,xmax+3*xint/2.,xint)+domain,
                       np.arange(xmin-xint/2.,xmax+3*xint/2.,xint)+domain,
                       data, cmap = color)
    s.set_clim(vmin=cmin,vmax=cmax)
    CS = plt.contour(np.arange(xmin,xmax+xint,xint)+domain,
                     np.arange(xmin,xmax+xint,xint)+domain,
                     data, colors='k',levels=levels_t)
    plt.clabel(CS, inline=1, fmt='%1.2f',fontsize=8)
    plt.scatter(stations[:,0]+domain, stations[:,1]+domain, color='k',s=2)
    maps.drawstates()
    fig = plt.gcf()
    circle=plt.Circle((domain,domain),100000,color='0.5',fill=False)
    fig.gca().add_artist(circle)
    circle=plt.Circle((domain,domain),200000,color='0.5',fill=False)
    fig.gca().add_artist(circle)
Beispiel #9
0
def arc_map(region=[-33.7, 149.4, -31.8, 151.8], res=1000, service='World_Topo_Map',epsg=4326,
            resolution='h',projection='mill'):
    '''
    Create and return the thingy
    Inputs:
        region:  [bot,left,top,right]
        service= one of 'World_Imagery', or 'World_Topo_Map'
            Imagery is more like blue marble, with no site labels
            Topo has inbuilt site labels, which render based on the resolution -> higher res for more zoomed in image.
        epsg: tell arcGIS where to pull image from, affects the image orientation
            Use 4326 for Sydney centric maps
            Use 3577 for Australia centred view
    '''

    # set up basemap projection
    # epsg is used to inform basemap that we will pull an image from ArcGIS servers
    # epsg=28355 does not work...
    # 3577 is centred at middle of Australia...
    # 4326 works for East Australia!
    m = Basemap(projection=projection, epsg=epsg,
                resolution=resolution,
                llcrnrlon=region[1], llcrnrlat=region[0],
                urcrnrlon=region[3], urcrnrlat=region[2])

    # Download backgroud to basemap's projection.
    #m.arcgisimage(service='World_Topo_Map', xpixels=res, verbose=True)
    m.arcgisimage(server='http://server.arcgisonline.com/ArcGIS', service=service,
                  xpixels=res, verbose=True)

    return m
Beispiel #10
0
def get_basemap():
# 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)
    shp_info = m.readshapefile('maps/st99_d00','states',drawbounds=True)
#   print(shp_info)
    return m
Beispiel #11
0
    def drawMap(self, var, strMonth):                

        m = Basemap( projection = 'cyl',llcrnrlon = p.lon0, \
                     llcrnrlat = self.lat0, urcrnrlon = self.lon0 + self.dxy * self.nX,\
                 urcrnrlat = self.lat0 + self.dxy * self.nY, resolution='i')

        var = np.flipud( np.ma.masked_array( var, var >= -0.2) )

        var = np.ma.masked_array( var, var < -10)

        levels = [ -0.1, -0.3, -0.5, -0.7, -0.9]

        im = m.pcolormesh( self.longitude, self.latitude,var, vmin = -0.9, vmax = 0.1)

        m.drawmeridians(np.arange( -10.0, 30, 5), labels = [1,0,0,1], fontsize = 10, rotation = 20)
        m.drawparallels(np.arange( 30.0, 60.0, 5), labels = [1,0,0,1], fontsize = 10, rotation = 20)
        
        m.drawcoastlines()
        m.drawcountries()
        plt.colorbar(im, orientation = 'vertical' , pad = 0.05 )


        plt.title( "CorrCoeff for month " + strMonth)


        plt.savefig( "corrCoeff" + strMonth + ".png", orientation = "landscape")
        plt.clf()
def ray_density(lat1, lon1, lat2, lon2,
                dt=1, gr_x=360, gr_y=180, 
                npts=180, projection='robin', 
                ray_coverage=False):
    '''
    Create the DATA array which contains the
    info for ray density
    '''
    global long_0

    mymap = Basemap(projection=projection, lon_0=long_0, lat_0=0)
    #npts=max(gr_x, gr_y)
    # grd[2]: longitude
    # grd[3]: latitude
    grd = mymap.makegrid(gr_x, gr_y, returnxy=True)

    lons, lats = mymap.gcpoints(lon1, lat1, lon2, lat2, npts)
    dist = locations2degrees(lat1, lon1, lat2, lon2)
    bap = int((dist - 97.0)*npts/dist)/2
    midlon = len(lons)/2
    midlat = len(lats)/2
    lons = lons[midlon-bap:midlon+1+bap]
    lats = lats[midlat-bap:midlat+1+bap]
    data = np.zeros([len(grd[2]), len(grd[3])])
    for i in range(len(lons)):
        xi, yi = point_finder(lons[i], lats[i], grd)
        # first one is latitude and second longitude
        try:
            #data[yi][xi] = dt/float(dist-97.0)
            data[yi][xi] += dt/len(lons)
        except Exception, e:
            print e
def main():
    unusable_name = 'unusable_%s.csv' % AREA
    unusable_data = csv.writer(open(unusable_name,'wb'))

    for i in range(2004,2013):
        m = Basemap(projection='merc',resolution=None,llcrnrlat=small_lat, \
        urcrnrlon=big_long,urcrnrlat=big_lat,llcrnrlon=small_long)
        fig = plt.figure(figsize=(11,11))
        ax = plt.subplot(111)
        m.drawmapboundary(fill_color='#1B1B1B')
    
        crime_dictionary = get_crimes(i,m,unusable_data)
        plot_crimes(crime_dictionary['nonviolent'],m)
        plot_crimes_violent(crime_dictionary['violent'],m) 
        plot_crimes_murder(crime_dictionary['murder'],m)
    
        plot_buildings(m)
        plot_streets(m)
        label_streets()

        output_file_name = '%s/%s_%s.png' % (AREA,AREA,str(i))
        ax.text(0.01,0.01,'https://github.com/oneschirm',color='white',\
        fontsize=12,transform=ax.transAxes)
        ax.text(0.9, 0.01, str(i),color='white', fontsize=20,transform=ax.transAxes)
        plt.savefig(output_file_name, dpi=150,bbox_inches='tight')
def drawMap(report):
	entries = get_site_status(report)
#	entries = {'unl.edu': [276, 0, 246, 0], 'desy.de': [107, 0, 0, 0], 'fnal.gov': [16, 0, 294, 0], 'N/A': [0, 0, 0, 0]}
	posList = get_positions(entries)

	#bounds = [(-60, -120), (60, 120)]
	#bounds = [(30, -10), (60, 40)]
	bounds = get_bounds(posList, margin = 10)

	matplotlib.pyplot.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
	fig = matplotlib.pyplot.figure(figsize=(12, 6))
	ax = matplotlib.pyplot.subplot(111)
	m = Basemap(projection='cyl', lat_0=0, lon_0=0,
		llcrnrlon=bounds[0][0], llcrnrlat=bounds[0][1],
		urcrnrlon=bounds[1][0], urcrnrlat=bounds[1][1])

	map_positions(m, posList)
	#posList = remove_all_overlap(posList)
	#print posList

	m.bluemarble()
	for pos in posList:
		draw_pie(ax, pos['info'], (pos['x'], pos['y']), pos['size'])
		ax.text(pos['x']+5, pos['y']+5, pos['site'], color='white', fontsize=8)
	fig.savefig(os.path.expanduser('~/map.png'), dpi=300)
def run(FILE_NAME):
    
    with h5py.File(FILE_NAME, mode='r') as f:

        name = '/Grid/IRprecipitation'
        data = f[name][:]
        units = f[name].attrs['units']
        _FillValue = f[name].attrs['_FillValue']
        data[data == _FillValue] = np.nan
        data = np.ma.masked_where(np.isnan(data), data)

        
        # Get the geolocation data
        latitude = f['/Grid/lat'][:]
        longitude = f['/Grid/lon'][:]

        
    m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=-180, urcrnrlon=180)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(-90, 91, 45))
    m.drawmeridians(np.arange(-180, 180, 45), labels=[True,False,False,True])
    m.pcolormesh(longitude, latitude, data.T, latlon=True)
    cb = m.colorbar()    
    cb.set_label(units)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}'.format(basename, name))
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Beispiel #16
0
def map_rupture(rupture):
    """
    Method for making a simple representation of a Rupture instance.
    This method draws the surface projection of the rupture on a map.

    Args:
        rupture: A Rupture instance.

    """
    rlats = rupture.lats
    rlons = rupture.lons

    minbufx = 0.2
    minbufy = 0.2
    lat1 = np.nanmin(rupture.lats)
    lat2 = np.nanmax(rupture.lats)
    dlat = lat2 - lat1
    bufy = np.max([dlat/2, minbufy])
    lon1 = np.nanmin(rupture.lons)
    lon2 = np.nanmax(rupture.lons)
    dlon = lon2 - lon1
    bufx = np.max([dlon/2, minbufx])
    m = Basemap(llcrnrlat=lat1-bufy,urcrnrlat=lat2+bufy, llcrnrlon=lon1-bufy,urcrnrlon=lon2+bufy)
    m.arcgisimage(service='World_Shaded_Relief', xpixels = 500, verbose= True)
    x, y = m(rlons, rlats)
    m.plot(x, y, 'r')
def test_geographic_histogram():
    tropics = UniformRandomPointSource()
    tropics.num_points = 100000
    tropics.bbox_min = ( -180, -23.4378 )
    tropics.bbox_max = ( 180, 23.4378 )

    try:
        pyplot.figure()
        pyplot.subplot(111, aspect='equal')

        mymap = Basemap(projection='moll',
                        lon_0=0,
                        resolution='l')
        mymap.drawcoastlines(color='white', zorder=5)
        mymap.fillcontinents(color='black', lake_color='white')

        artists = geographic_histogram( mymap,
                                        tropics.points(),
                                        bbox_lowerleft=(-180, -90),
                                        bbox_upperright=(180, 90)
                                        )

        pyplot.savefig('tracktable_geographic_histogram_test.png', figsize=(4, 4), dpi=150)
        return True
    except Exception, e:
        traceback.print_exc()
        return False
def create_map():
    poverty_data, error = world_bank_api.most_recent_poverty_data()
    if error is not None:
        print(error)
        return

    poverty_data = utils.dictify_list_of_dicts(poverty_data, 'country_code')

    world_map = Basemap()
    world_map.readshapefile('borders', 'countries')
    country_to_color, country_names = decide_colors_and_countries(world_map, poverty_data)

    axes = plt.gca() # get current axes instance
    for nshape, seg in enumerate(world_map.countries):
        country_name = country_names[nshape]
        if country_name not in country_to_color:
            print('could not find: ' + country_name)
            continue
        color = country_to_color[country_name]
        poly = Polygon(seg, facecolor=color, edgecolor=color)
        axes.add_patch(poly)

    add_legend()
    fig = plt.gcf()
    fig.set_size_inches(30, 15)

    plt.axis('off')
    fig.savefig('countries_by_poverty_rate_world_bank_data.png', dpi=100,
                bbox_inches='tight',
                pad_inches=0)
Beispiel #19
0
def do_calc(LATLIMS_AM, LONLIMS_AM, indir, outdir):
    land_checker = Basemap()
    if land_checker.is_land(LATLIMS_AM, LONLIMS_AM):
        print "SOS! Sorry you have selected a land pixel!"
        pygame.mixer.music.load("SOS.midi")
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            # plot animado?
            time.sleep(1)
    else:
        dataAM = extract_series(LATLIMS_AM, LONLIMS_AM, indir)
        data_am = np.double(dataAM["Series"])
        if all(np.isnan(a) for a in data_am):
            print "THE SOUND OF SILENCE. Also, BATMAN. Everything is Rest and NaN"
            pygame.mixer.music.load("Batman_song.midi")
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy():
                # Anim plot? See Matplotlib.Animation
                time.sleep(1)
        else:
            am = get_music(data_am)

            music = pygame.mixer.Sound("Oc.midi")
            pygame.mixer.music.load("Oc.midi")
            pygame.mixer.music.play()
            anim = plot_animation(
                data_am,
                (u"Music from Lat = %.2f Lon = %.2f" % (dataAM["Lat"], dataAM["Lon"])),
                "serie.png",
                t_max=36000,
            )  # music.get_length())
def prepare_map0(coordinates, res):
    m = Basemap(llcrnrlon=coordinates[0], llcrnrlat=coordinates[2],
                urcrnrlon=coordinates[1], urcrnrlat=coordinates[3], resolution=res)
    fig = plt.figure()
    ax = plt.subplot(111)
    m.ax = ax
    return fig, m, ax
Beispiel #21
0
def contourMap(grdROMS, tlon, tlat, mydata1, mydata2, mydata3, var, mytype, currentdate):

    plt.figure(figsize=(10,10), frameon=False)
    
    map = Basemap(lon_0=25,boundinglat=50,
                      resolution='l',area_thresh=100.,projection='npstere')
    
    x, y = list(map(tlon,tlat))

    map.drawcoastlines()
    map.fillcontinents(color='grey')
    map.drawcountries()

    if var=='wind':
        levels = np.arange(np.min(mydata3),np.max(mydata3),0.1)
   
        CS1 = map.contourf(x, y, mydata3, levels, cmap=cm.get_cmap('RdYlBu_r',len(levels)-1) )#,alpha=0.5)
        plt.colorbar(CS1, orientation='vertical', extend='both', shrink=0.5)
            
        if mytype=="REGSCEN":
          step=8
        else:
          step=1
        map.quiver(x[0:-1:step,0:-1:step],y[0:-1:step,0:-1:step],
            mydata1[0:-1:step,0:-1:step],mydata2[0:-1:step,0:-1:step],
            scale=400)
   
  #  plt.title('Var:%s - depth:%s - time:%s'%(var,grdROMS.time))
    plotfile='figures/'+str(var)+'_'+str(mytype)+'_time_'+str(currentdate)+'.png'
    if not os.path.exists('figures'):
        os.makedirs('figure')
    plt.savefig(plotfile)
    print("Saved figure: %s"%(plotfile))
Beispiel #22
0
    def plot(self):
        ''' plot some random stuff '''
        # random data
        '''data = [random.random() for i in range(2)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.hold(False)

        # plot data
        ax.plot(data, '*-')'''
        m = Basemap(projection='robin',lon_0=0,resolution='c')#,latlon=True)
        m.bluemarble(scale=0.2)
        for friend in rpc.bridge.getFriendList():
          print ''
          pd = rpc.bridge.getPeerDetails(friend)
          print pd['name']
          print pd['extAddr']
          ld = gi.record_by_addr(pd['extAddr'])
          print ld
          if ld:
            print ld['latitude'],ld['longitude']
            x, y = m(ld['longitude'],ld['latitude'])
            #m.scatter(x, y,30,marker='o',color='k')
            plt.plot(x, y,'ro')
            plt.text(x,y,pd['name'],fontsize=9,
                    ha='center',va='top',color='r',
                    bbox = dict(boxstyle="square",ec='None',fc=(1,1,1,0.5)))
            #plt.text(x,y,pd['name'],fontsize=14,fontweight='bold',
            #        ha='center',va='center',color='r')
        # refresh canvas
        self.canvas.draw()
 def plot_filtered_diff(self):
     """
     function for plotting the difference of filtered vorticity
     """
     
     w_diff, lon, lat, mask = self.vorticity_filter()
     
     south = lat.min(); north =lat.max()
     west = lon.min(); east = lon.max()
     
     timeformat = '%Y%m%d-%H%M'
     for i in range(len(self.time)):
         fig = plt.figure(figsize=(10,8))
         basemap = Basemap(projection='merc',llcrnrlat=south,urcrnrlat=north,\
                   llcrnrlon=west,urcrnrlon=east, resolution='h')
         
         basemap.drawcoastlines()
         basemap.fillcontinents(color='coral',lake_color='aqua')
         basemap.drawcountries()
         basemap.drawstates()  
         
         llons, llats=basemap(lon,lat)   
         con = basemap.pcolormesh(llons,llats,w_diff[i,:,:])
         #con.set_clim(vmin=-0.0003, vmax=0.0003)
         cbar = plt.colorbar(con, orientation='vertical')
         cbar.set_label("vorticity")
         #plt.show()
         timestr = datetime.strftime(self.time[i], timeformat)
         plt.title('vorticity at %s'%timestr)
         plt.savefig(self.wdr+'/vorticity_figure/vorticity_diff/'+str(i)+'.png')
         print "Saving figure %s to ROMS figure directory"%str(i)
def render_nextbus_dataframe(route, nextbus_df):
    """Plots the NextBus Vehicle Location's Panda Data frame to a
    Matplotlib and Basemap Geospatial image."""

    min_long = min(nextbus_df.lon)
    min_lat = min(nextbus_df.lat)
    max_long = max(nextbus_df.lon)
    max_lat = max(nextbus_df.lat)

    bmap = Basemap(llcrnrlon=min_long, llcrnrlat=min_lat,
                   urcrnrlon=max_long, urcrnrlat=max_lat,
                   ellps='WGS84',
                   resolution='h', area_thresh=1000)

    bmap.drawmapboundary(fill_color='white')

    bmap.scatter(nextbus_df.lon, nextbus_df.lat,
                 marker='d', edgecolor='g', facecolor='g', alpha=0.5)
    plt.xlabel('Longitude')
    plt.ylabel('Latitude')
    plt.axis([min_long, max_long, min_lat, max_lat])
    plt.title('NextBus Vehicle Locations for route {}'.format(route))
    plt.grid(True)
    # plt.legend(loc='lower center')
    plt.savefig('nextbus_vehicle_locations.png', fmt='png', dpi=600)
    # plt.show()
    # Other components (like GMaps plotting) will also use Matplotlib, so
    # it's better to clear the figure that Matplotlib generated
    plt.clf()
def draw_latlon(llclat, urclat, llclon, urclon, rsphere=6371200, resolution='h', area_thresh=0.1, projection='merc'):
    m = Basemap(llcrnrlat=llclat, urcrnrlat=urclat,
                llcrnrlon=llclon, urcrnrlon=urclon,
                rsphere=rsphere, resolution=resolution,
                area_thresh=area_thresh, projection=projection)
    m.drawcoastlines()
    m.drawcountries()
Beispiel #26
0
class Mapper:
    def __init__(self, state):
        with open(state_boundries_file_loc) as f:
            for line in f:
                line = line.rstrip().split(',')
                if line[0].lower() == state.lower():
                    ur_lon, ll_lat = float(line[1]), float(line[3])
                    ll_lon, ur_lat = float(line[2]), float(line[4])
                    center_lon = ll_lon + ur_lon
                    if math.copysign(1, ll_lon) != math.copysign(1, ur_lon):
                        center_lon = -180 + center_lon
                    else:
                        center_lon = center_lon / 2
                    center_lat = (ll_lat + ur_lat) / 2

                    self.m = Basemap(llcrnrlon = ll_lon, llcrnrlat = ll_lat,
                                urcrnrlon = ur_lon, urcrnrlat = ur_lat,
                                projection = 'lcc', lat_1 = center_lat,
                                lon_0 = center_lon)
    def setBorders(self):
        self.m.readshapefile(states_shapefile_loc,
                            'states', drawbounds = True)

    def plotPoint(self, lat, lon):
        self.m.plot(lat, lon, latlon=True, marker='o', color='m')

    def displayMap(self):
        plt.show()
Beispiel #27
0
def main():
    ds = nC.Dataset("../../grid_arctic.nc")
    data = ds.variables["tas"][:].squeeze()
    lon2d_nc = ds.variables["lon"][:]
    lat2d_nc = ds.variables["lat"][:]

    rplon, rplat = -115.850877297, 21.1216893478
    lon_0 = -123.403723307

    basemap = Basemap(projection="rotpole", o_lon_p=rplon, o_lat_p=rplat,
                      lon_0=lon_0 - 180,
                      llcrnrlon=lon2d_nc[-1, -1], llcrnrlat=lat2d_nc[-1, -1],
                      urcrnrlon=lon2d_nc[0, 0], urcrnrlat=lat2d_nc[0, 0],
                      resolution="l")

    import matplotlib.pyplot as plt

    im = basemap.etopo()

    x, y = basemap(lon2d_nc, lat2d_nc)
    # basemap.contourf(x, y, data)
    # basemap.colorbar()
    # basemap.drawcoastlines()
    # basemap.drawmeridians(np.arange(-180, 180, 30))
    # basemap.drawparallels(np.arange(-90, 90, 40))
    plt.show()

    pass
def calculator(DATA, passed_staev, gr_x, npts, start, end, 
                    projection='robin', ray_coverage=False): 
    global long_0

    mymap = Basemap(projection=projection, lon_0=long_0, lat_0=0)
    nonzero = []
    gr_y = gr_x
    grd = mymap.makegrid(gr_x, gr_y, returnxy=True)
    for i in range(start, end):
        print i,
        sys.stdout.flush()
        data, exist_flag = ray_density(passed_staev[i][4], passed_staev[i][5],
                        passed_staev[i][0], passed_staev[i][1], 
                        dt=passed_staev[i][2], 
                        gr_x=gr_x, gr_y=gr_y, npts=npts, 
                        projection=projection, 
                        ray_coverage=ray_coverage)
        if not i == end-1:
            if not exist_flag: 
                continue
        if DATA is None: DATA = data.copy()
        else: DATA += data
        nonzero_tmp = np.nonzero(data)
        for j in range(len(nonzero_tmp[0])):
            nonzero.append((nonzero_tmp[0][j], nonzero_tmp[1][j]))
    fi = open('MAP_OUTPUT/DATA-' + str(start), 'w')
    pickle.dump(DATA, fi)
    fi.close()
    fi = open('MAP_OUTPUT/nonzero-' + str(start), 'w')
    pickle.dump(nonzero, fi)
    fi.close()
def plot_brights(ax, path, star, regionList, goal=False):
    '''
    Components of this routine:
        Projected brightness map
         
    Please note that this has been modified for use in diagnostic plots, 
    there should really be a way to specify a windowNumber for real data
    '''
    currentWindow = 0

    ###########################
    # Make the brightness map #
    ###########################
    img = make_bright_image(star, regionList, currentWindow, goal=goal)
    
    plt.imsave(path + "temp.jpg", img, cmap='hot', vmin=0.85, vmax=1.15)
    plt.imshow(img, cmap='hot')
    #Create the plot
    bmap = Basemap(projection='moll', lon_0 = 0, ax=ax)
    bmap.warpimage(path + "temp.jpg", ax=ax)
    
    if goal:
        ax.set_title("Desired Map")
    else:
        ax.set_title("Average Map")
Beispiel #30
0
    def getMDAreas(self,dx=20000,dy=20000,
                    llcrnrlon=-119.2,
                    llcrnrlat=23.15,
                    urcrnrlon=-65.68,
                    urcrnrlat=48.7):
        bmap = Basemap(projection="lcc",
                       llcrnrlon=llcrnrlon,
                       llcrnrlat=llcrnrlat,
                       urcrnrlon=urcrnrlon,
                       urcrnrlat=urcrnrlat,
                       resolution='l',
                       lat_0=38.5,
                       lat_1=38.5,
                       lon_0=-97.0)
        from matplotlib.nxutils import points_inside_poly
        xs = np.arange(bmap.llcrnrx,bmap.urcrnrx + dx,dx)
        ys = np.arange(bmap.llcrnry,bmap.urcrnry + dy,dy)
        lon,lat,x_grid,y_grid = bmap.makegrid(xs.shape[0],ys.shape[0],returnxy=True)
        x, y = x_grid.flatten(), y_grid.flatten()
        points = np.vstack((x,y)).T
        
        nx = xs.shape[0]
        ny = ys.shape[0]
        areas = np.zeros((self.data.shape[0],))

        for i in xrange(self.data.shape[0]):
            md_x,md_y = bmap(self.data['Lon'][i],self.data['Lat'][i])
            poly_xy = np.vstack((md_x,md_y)).T
            areas[i] = np.nonzero(points_inside_poly(points,poly_xy))[0].shape[0] * dx * dy / 1000**2

        return areas