def plot_locations(result,amenity,top): 
    import pandas as pd
    import numpy
        
    lat = []
    lon = []
    for res in result:
        lat.append(res['pos'][0])
        lon.append(res['pos'][1])       
    
    geo = pd.DataFrame(lat, columns = ['lat'])
    geo['lon'] = lon
    
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt
     
    my_map = Basemap(projection='merc', lat_0=geo.median()[0], lon_0=geo.median()[1],
        resolution = 'h', area_thresh = .1,
        llcrnrlon=geo.min()[1]-.1, llcrnrlat=geo.min()[0]-.1,
        urcrnrlon=geo.max()[1]+.1, urcrnrlat=geo.max()[0]+.1)
     
    my_map.drawrivers()
    my_map.drawcounties()
    my_map.fillcontinents(color='tan')
    my_map.drawmapboundary()
    my_map.drawcoastlines()
   
    x,y = my_map(lon, lat)
    my_map.plot(x,y, 'bo', markersize=2)
    
    title = 'Map Showing %s Added by \"%s\"\nThe Top %s Editor' % (str(amenity).title(),str(top),str(amenity).title())
    plt.title(title)
    p = plt.show()
    
    return p
    def show_route(self):
        '''
        Display the route coordinates on a map of Tompkins County
        '''

        # plot basemap w/ state and county lines, etc
        fig = plt.figure()
        m = Basemap(llcrnrlon=-76.8, llcrnrlat=42.2, urcrnrlon=-76.2, \
            urcrnrlat=42.7, rsphere=(6378137.00,6356752.3142), resolution='l', \
            projection='merc')
        m.shadedrelief()
        m.drawcoastlines()
        m.drawstates()
        m.drawcountries()
        m.drawcounties()

        # plot ny state water features
        m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDFlowline','water', color='LightSteelBlue', linewidth=2.)
        m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDArea','water_area', drawbounds=False)
        m.readshapefile('data\\water\\NHD_M_36_New_York_ST\\NHDWaterbody','lakes', drawbounds=False)
        for lake in m.lakes + m.water_area:
            poly = Polygon(lake, facecolor='LightSteelBlue', edgecolor='CornflowerBlue')
            plt.gca().add_patch(poly)

        # read and plot tompkins county shapefile
        m.readshapefile('data\\parcels\\ParcelPublic2016_WGS84', 'parcels')

        # plot route coordinates
        m.plot(self.coordinates[:,0], self.coordinates[:,1], '.-',
               latlon=True, c='FireBrick', lw=2.)

        # finalize and show plot
        fig.show()
 def make_NYC_basemap(self, ax=None, lllat=40.45, urlat=40.95, lllon=-74.3, urlon=-73.68):
     '''
     This function creates the initial NYC basemap. It is only called once (in the initialization
     of an NYC_school_interactive_map instance), since it has a relatively long run-time (it queries
     the ESRI REST server to get a relatively high-resolution basemap image).
     ''' 
         
     fig = plt.figure(figsize=(12,12))
     ax = plt.subplot(111)
         
     m = Basemap(ax = ax, 
                    lon_0=(urlon + lllon)/2,
                    lat_0=(urlat + lllat)/2,
                    llcrnrlat=lllat, urcrnrlat=urlat,
                    llcrnrlon=lllon, urcrnrlon=urlon,
                    resolution='f', epsg=3857) ###epsg is the projection code for ESRI world shaded relief basemap
 
     #m.arcgisimage queries the ESRI REST API (server below) to get the basemap 
     #http://server.arcgisonline.com/arcgis/rest/services
     m.arcgisimage(service='World_Shaded_Relief', xpixels = 1500)
 
     # Add county lines, since boroughs map onto counties
     m.drawcounties(linewidth=0.5)
     
     return m, ax, fig
def plot_nc(lons, lats, precips):
    m = Basemap(width=200000, height=200000, projection='stere',
                lat_0=lat_0, lon_0=lon_0)
    lon, lat = np.meshgrid(lons, lats)
    xi, yi = m(lon, lat)
    cs = m.pcolor(xi, yi, precips[0])
    m.drawstates()
    m.drawcounties()
    cbar = m.colorbar(cs, location='bottom', pad='10%')
    plt.show()
Beispiel #5
0
def CO2nWind(file,outputdir):
  """
  Outputs plots of CO2 in the lowest level and 10m winds
  """
  import matplotlib
  matplotlib.use('Agg')
  import numpy as np
  import sys
  from netCDF4 import Dataset
  import matplotlib.pyplot as plt
  from mpl_toolkits.basemap import Basemap
  # read in file and vars
  f = Dataset(file,'r')
  wrfeta = f.variables['ZNU'][0][:]
  times = f.variables['Times'][:]
  wrflats = f.variables['XLAT'][0][:]
  wrflons = f.variables['XLONG'][0][:]
  var = f.variables['CO2_ANT'][:,0,:,:]
  u = f.variables['U'][:,0,:,:]
  v = f.variables['V'][:,0,:,:]
  # destagger u/v
  u = (u[:,:,:-1] + u[:,:,1:])/2.
  v = (v[:,:-1,:] + v[:,1:,:])/2.

  # four corners of domain
  wrflat_s = wrflats[0,len(wrflats)-1]
  wrflat_n = wrflats[len(wrflats)-1,len(wrflons[0])-1]
  wrflon_w = wrflons[0,0]
  wrflon_e = wrflons[len(wrflats)-1,len(wrflons[0])-1]

  z = 0 # assuming lowest level of model

  # set up map
  map = Basemap(projection='merc',llcrnrlon=wrflon_w,urcrnrlon=wrflon_e,llcrnrlat=wrflat_s,urcrnrlat=wrflat_n,resolution='i')
  map.drawstates()
  map.drawcounties()
  map.drawcoastlines()
  x,y = map(wrflons,wrflats)

  # loop through times
  for t in range(len(times)):
    timestr = ''.join(times[t,:])
    map.drawstates(color='gray',linewidth=1)
    map.drawcounties(color='white')
    map.drawcoastlines(color='gray',linewidth=1)
    plt1 = map.pcolormesh(x,y,var[t,:,:],vmin=380,vmax=450)
    #plt1 = map.pcolormesh(x,y,var[t,:,:],vmin=np.amin(var),vmax=np.amax(var))
    winds = map.barbs(x[::20,::20],y[::20,::20],u[t,::20,::20]*1.94,v[t,::20,::20]*1.94,length=6,color='white') # *1.94 to convert m/s to knots (barb convention)
    colorbar = map.colorbar(plt1,"right", size="5%",pad="2%")
    colorbar.set_label(f.variables['CO2_ANT'].description+' '+f.variables['CO2_ANT'].units)
    plt.title('WRF output valid: '+timestr)
    plt.savefig(outputdir+'/%03d_' % (t) +timestr+'_CO2_wind.png')
    plt.clf()
def _basemap_district(min_lat, min_lon, max_lat, max_lon):
        """ This function creates a Basemap instance that is a map of a District of chicago

        :param min_lat, min_lon, max_lat, max_lon: integers or floats representing  vertices of the map
        :return district_map
        """
        district_map = Basemap(llcrnrlon=min_lon, llcrnrlat=min_lat, urcrnrlon=max_lon, urcrnrlat=max_lat, projection="merc", resolution = 'h')
        district_map.drawcoastlines()
        district_map.drawcountries()
        district_map.drawcounties()
        district_map.drawmapboundary()
        district_map.drawrivers(color='#0000ff')
        return district_map
Beispiel #7
0
def basicsurfmap(file,varstr,outputdir):
  """
  Creates plots for each timestep of a file
  for the specified variable and outputs them
  to a specified directory
  """
  import matplotlib
  matplotlib.use('Agg')
  import numpy as np
  import sys
  from netCDF4 import Dataset
  import matplotlib.pyplot as plt
  from mpl_toolkits.basemap import Basemap
  # read in file and vars
  f = Dataset(file,'r')
  wrfeta = f.variables['ZNU'][0][:]
  times = f.variables['Times'][:]
  wrflats = f.variables['XLAT'][0][:]
  wrflons = f.variables['XLONG'][0][:]
  var = f.variables[varstr][:]
  # four corners of domain
  print wrflats.shape
  print wrflons.shape
  print wrflons[0].shape
  wrflat_s = wrflats[0,len(wrflats)-1]
  wrflat_n = wrflats[len(wrflats)-1,len(wrflons[0])-1]
  wrflon_w = wrflons[0,0]
  wrflon_e = wrflons[len(wrflats)-1,len(wrflons[0])-1]
 
  z = 0 # assuming lowest level of model

  # set up map
  map = Basemap(projection='merc',llcrnrlon=wrflon_w,urcrnrlon=wrflon_e,llcrnrlat=wrflat_s,urcrnrlat=wrflat_n,resolution='i')
  map.drawstates()
  map.drawcounties()
  map.drawcoastlines()
  x,y = map(wrflons,wrflats)
 
  # loop through times
  for t in range(len(times)):
    timestr = ''.join(times[t,:])
    map.drawstates()
    map.drawcounties()
    map.drawcoastlines()
    plt1 = map.pcolormesh(x,y,var[t,z,:,:],vmin=np.amin(var),vmax=np.amax(var))
    colorbar = map.colorbar(plt1,"right", size="5%",pad="2%")
    colorbar.set_label(f.variables[varstr].description+' '+f.variables[varstr].units)   
    plt.title('WRF output valid: '+timestr)
    plt.savefig(outputdir+'/%03d_' % (t) +timestr+'_'+varstr+'.png')
    plt.clf()
Beispiel #8
0
def write_map_file(filename, known, unknown, width, height, dpi, labels_col, title):
    data = unknown.append(known, True, False)
    enlarge_by = 0.1
    plt.figure(num=None, figsize=(width, height), dpi=dpi, facecolor="w", edgecolor="k")
    data = data.loc[data.modern_lat != 0.0, :]
    ll = data.modern_lat.min(), data.modern_lon.min()
    ur = data.modern_lat.max(), data.modern_lon.max()
    adj = tuple((ur[i] - ll[i]) * enlarge_by for i in range(2))
    ll = tuple(ll[i] - adj[i] for i in range(2))
    ur = tuple(ur[i] + adj[i] for i in range(2))
    lat0 = ll[0] + ((ur[0] - ll[0]) / 2.0)
    lon0 = ll[1] + ((ur[1] - ll[1]) / 2.0)
    bmap = Basemap(
        projection="merc",
        resolution="l",
        lon_0=lon0,
        lat_0=90.0,
        lat_ts=lat0,
        llcrnrlat=ll[0],
        llcrnrlon=ll[1],
        urcrnrlat=ur[0],
        urcrnrlon=ur[1],
    )
    bmap.shadedrelief()
    bmap.drawmapboundary()
    bmap.drawmeridians(np.arange(0, 360, 5), labels=[0, 0, 0, 1], fontsize=10)
    bmap.drawparallels(np.arange(-90, 90, 5), labels=[1, 0, 0, 0], fontsize=10)
    bmap.drawcounties(linewidth=1)
    for disp, col in [("known", "c"), ("unknown", "m"), ("tentative", "b")]:
        i = data.disposition == disp
        lats = [lat for lat in list(data.loc[i, "modern_lat"]) if lat != 0.0]
        lons = [lon for lon in list(data.loc[i, "modern_lon"]) if lon != 0.0]
        x, y = bmap(lons, lats)
        bmap.scatter(x, y, 8, marker="o", color=col, label=disp)
        if filename:
            labels = []
            for s in data.loc[i, labels_col]:
                labels.append(s if type(s) == unicode else u"")
            for label, xi, yi in zip(labels, x, y):
                plt.text(xi, yi, label)
    plt.title(title)
    plt.legend()
    if filename:
        plt.savefig(filename, dpi=dpi)
    else:
        plt.show()
def drawMapOfSimilarityMatrix(graph, similarityMatrix, quality, targetCounty,
                              denominator, classesToDraw=5):
    if quality == 'high':
        basemapResolution = 'i'
        DPI = 500
        reliefScale = 1
        figSize = (10, 5)
    else:
        basemapResolution = 'c'
        DPI = 250
        reliefScale = 0.5
        figSize = (5, 2.5)

    plt.figure(figsize=figSize)
    m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49,
                projection='lcc', lat_1=33, lat_2=45, lon_0=-95,
                resolution=basemapResolution)
    m.shadedrelief(scale=reliefScale)
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    if quality == 'high':
        m.drawcounties()

    toDraw = similarityMatrix[targetCounty]

    colors = getDivergingColorList(classesToDraw)
    classBucketSize = 1 / float(classesToDraw - 1)

    for county, matches in toDraw.iteritems():
        x, y = m(graph.vs.find(name=county)["longitude"],
                 graph.vs.find(name=county)["latitude"])
        percentSimilar = matches / float(denominator)
        if percentSimilar == 1:
            colorOffset = int(classesToDraw - 1)
        else:
            colorOffset = int(percentSimilar // classBucketSize)
        m.scatter(x, y, 3, marker='o', color=colors[colorOffset])

    mapName = "proportion-map-{0}-{1}.png".format(
        targetCounty, datetime.datetime.today())
    plt.savefig(mapName, dpi=DPI, bbox_inches='tight')
Beispiel #10
0
    def __include_basemap(self, ax, shpfile, POT, locs, colors, resolution='i', projection='tmerc', **basemap_kwargs):
        from mpl_toolkits.basemap import Basemap
        from matplotlib.patches import Polygon

        if 'llcrnrlon' not in basemap_kwargs.keys():
            basemap_kwargs.update({'llcrnrlon': self.ll.lon.min()-.01})
        if 'llcrnrlat' not in basemap_kwargs.keys():
            basemap_kwargs.update({'llcrnrlat': self.ll.lat.min()-.01})
        if 'urcrnrlon' not in basemap_kwargs.keys():
            basemap_kwargs.update({'urcrnrlon': self.ll.lon.max()+.01})
        if 'urcrnrlat' not in basemap_kwargs.keys():
            basemap_kwargs.update({'urcrnrlat': self.ll.lat.max()+.01})
        if projection == 'tmerc':
            if 'lat_0' not in basemap_kwargs.keys():
                basemap_kwargs.update({'lat_0': (self.ll.lat.min()+self.ll.lat.max())/2.})
            if 'lon_0' not in basemap_kwargs.keys():
                basemap_kwargs.update({'lon_0': (self.ll.lon.min()+self.ll.lon.max())/2.})

        map = Basemap(ax=ax, resolution=resolution, projection=projection, **basemap_kwargs)
        
        parallels = np.arange(basemap_kwargs['llcrnrlat'], basemap_kwargs['urcrnrlat'],.1)
        map.drawparallels(parallels,labels=[True,False,False,False])
        
        meridians = np.arange(basemap_kwargs['llcrnrlon'], basemap_kwargs['urcrnrlon'],.1)
        map.drawmeridians(meridians,labels=[False,False,False,True])
        map.drawcounties()

        if shpfile is not None:
            map.readshapefile(shpfile, 'watersheds')

            w_names = []
            for shape_dict in map.watersheds_info:
                w_names.append(shape_dict['GAGE_ID'])

            for loc, c in zip(locs, colors):
                seg = map.watersheds[w_names.index(loc)]
                poly = Polygon(seg, facecolor=c,edgecolor=c, alpha=.5)
                ax.add_patch(poly)
        return map    
Beispiel #11
0
    def grid_plot(self):
        """
        function for visualizing the generated grid
        """
        
        lon, lat, dx, dy  = self.rectilinear(self.nx,self.ny)
        pdb.set_trace()
        west=-95.42; east=-93.94
        south=28.39;  north=29.90
        fig = plt.figure(figsize=(10,10))
        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.drawcounties()
        basemap.drawstates()  
        basemap.drawrivers(color='b')

        llons, llats=basemap(lon,lat)
        basemap.plot(llons, llats, color='k', ls='-', markersize=.5)
        basemap.plot(llons.T, llats.T, color='k', ls='-', markersize=.5)
        plt.show()    
size=(pop/np.max(pop))*100    # 绘制散点图时图形的大小,如果之前pop不转换为浮点型会没有大小不一的效果

# size=(gdp/np.max(gdp))*100    # 绘制散点图时图形的大小,如果之前pop不转换为浮点型会没有大小不一的效果

map = Basemap(projection='stere', 
              lat_0=35, lon_0=110,
              llcrnrlon=82.33, 
              llcrnrlat=3.01, 
              urcrnrlon=138.16, 
              urcrnrlat=53.123,resolution='l',area_thresh=10000,rsphere=6371200.)


map.drawcoastlines()   
map.drawcountries()    
map.drawcounties()
map.readshapefile("data/python-code/resources/CHN_adm_shp/CHN_adm1",'states',drawbounds=True)
map.drawmapboundary()


parallels = np.arange(0.,90,10.) 
map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # 绘制纬线

meridians = np.arange(80.,140.,10.)
map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) # 绘制经线


x,y = map(lon,lat)

# map.scatter(x,y,edgecolors='r',facecolors='r',marker='*',s=320)
Beispiel #13
0
    plt.scatter(new_UND_lons,new_UND_lats,s=480., marker='o',c='#CC00FF',edgecolor='k',linewidth=0.125,zorder=7, alpha=1.0, label='CLAMPS')

#atts_info = m.readshapefile(home_directory+'/spotter_network_density/shapefiles/nexrad_attributes/current_nexattr','atts',drawbounds=False)
#TVS_count=0
#for info, att in zip(m.atts_info, m.atts):
#    if info['TVS'] == 'TVS' and info['MESO'] != 'NONE' and int(info['RANGE']) <= 100:
#        TVS_count=TVS_count+1
#        if TVS_count==0:
#            plt.scatter(att[0],att[1],s=90., marker='v',c='r',edgecolor='r',zorder=8, alpha=1.0, label='Tor. Vortex Signature')
#        else:
#            plt.scatter(att[0],att[1],s=90., marker='v',c='r',edgecolor='r',zorder=8, alpha=1.0)
#plt.legend( loc=2, borderaxespad=0.,prop={'size':10})
leg = plt.legend( loc=2, borderaxespad=0.,prop={'size':10})
leg = leg.get_frame()
leg.set_facecolor('#F1F0F2')
m.drawcounties(color='#D0D0D0', zorder=3)

#PLOT RADAR DATA*******************************************************************
import glob
import os
#/data/ldm/nexrad2/KTLX/dir.list 
search_dir = "/data/ldm/nexrad2/" +nearest_radar + '/dir.list'
list_of_completed = np.genfromtxt(search_dir, dtype=str)

radar = pyart.io.read("/data/ldm/nexrad2/" + nearest_radar + "/" + list_of_completed[-1][1])
display = pyart.graph.RadarMapDisplay(radar)
#set projection and map for PyArt. It should be the same as the first projection
CS = display.plot_ppi_map('reflectivity', 0, vmin=10, vmax=75,
                     lat_0=UND_lats[0],lon_0=UND_lons[0],
                     width=map_width,height=map_height, projection=projection_type,
                     resolution='i',colorbar_flag=False,title_flag=False,
fig = plt.figure(figsize=(8, 6))
plt.subplots_adjust(left=0.01,right=0.9,top=0.97,bottom=0.05,wspace=0.15,hspace=0.05)
ax = plt.subplot(111)

x1 = -74.3
x2 = -73.7
y1 = 40.5
y2 = 40.925

m = Basemap(llcrnrlon=x1,llcrnrlat=y1,urcrnrlon=x2,urcrnrlat=y2,resolution='h',projection='merc',lat_ts=1.)

m.drawcoastlines()
m.fillcontinents(color="#DDDDDD")
m.drawcountries()
m.drawmapboundary(fill_color='#99ccff')
m.drawcounties()
vmin = 5.
vmax = 35.

cmap = plt.cm.spring
for feature in neighborhoods["features"]:
    if feature["properties"]["neighborhood"].upper() in list(coop_hood_avgs.neighborhood):
        hood = feature["properties"]["neighborhood"].upper()
        value = coop_hood_avgs_trans[hood]["avg_gross"]
        color = cmap((value - vmin)/(vmax - vmin))[:3]

    else:
        color = "#666666"

    some_points = feature["geometry"]["coordinates"]
    lons, lats = np.array(some_points).T
Beispiel #15
0
# set the colormap to jet.
#m.pcolormesh(x,y,data,shading='flat',cmap=plt.cm.jet)

# Add a colorbar/legend
cbar = m.colorbar(contour, ticks=[0.25, 1.0, 1.75, 2.75, 4.00])
cbar.ax.set_yticklabels(['Pea','Quarter','Golfball','Baseball','Grapefruit'])

################################################
# Build Map Features, like continents, states, #
# lat/lon lines, and other physical features   #
################################################
m.drawcoastlines(linewidth=0.75,zorder=5)
m.fillcontinents(color='#e6e6e6',lake_color='#b3ffff')
m.drawcountries(linewidth=1.0,zorder=7)
m.drawstates(linewidth=0.5,zorder=6)
m.drawcounties(linewidth=0.3,color='gray',zorder=5)
m.drawmapboundary(fill_color='#b3ffff')

##############################################
# Add a title, and then show the plot.       #
# Save the plot as images to disk if desired #
##############################################
plt.title('24-Hour Radar Hail Tracks\nEnding '+validtime+'')
plt.savefig('hail.png', dpi=300, bbox_inches='tight')
#plt.show()
print 'Finished creating image.'
viewimg = raw_input('Would you like to view the image? ')
if viewimg == 'y' or viewimg == 'yes':
    call(["open", "hail.png"])
    print 'Your image should appear. Enjoy your day!'
else:
    # create figure and axes instances
    fig = plt.figure(figsize=(16,16))
    ax = fig.add_axes([0.1,0.1,0.9,0.9])
    
    # llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
    # are the lat/lon values of the lower left and upper right corners
    # of the map.
    # resolution = 'i' means use intermediate resolution coastlines.
    # lon_0, lat_0 are the central longitude and latitude of the projection.
    m = Basemap(llcrnrlon=-122.2332,llcrnrlat=37.0793,urcrnrlon=-121.4010,urcrnrlat=37.5141, \
                rsphere=6371200.,resolution='h',projection='stere',lon_0=-122,lat_0=37.25, anchor='C')
    
    # can get the identical map this way (by specifying width and
    # height instead of lat/lon corners)
    m.drawcoastlines()
    m.drawcounties(linewidth=1)
    m.fillcontinents(color='coral',lake_color='aqua')
    # draw parallels and meridians.
    m.drawmeridians(np.arange(-122,-120.,0.25), dashes=[3,3], color='b', labels=[0,0,0,1], ax=ax)
    m.drawparallels(np.arange(37.,38.,0.25), dashes=[3,3], color='b', labels=[1,0,0,0], ax=ax)
    m.drawmapboundary(fill_color='aqua')
    
    # Pick up one user from the top 10 users.
    user = result[4]['_id']
    print user

    # Extract all the locations this user added.
    user_data = db.sj.find({'created.user':user})
    pos_x  = []
    pos_y = []
    i = 0
Beispiel #17
0
    ax = fig.add_subplot(1,1,1)
    m = Basemap(width=1400000,height=1100000,rsphere=6371229.0,
                projection='lcc',lat_1=25.,lat_2=25.,lon_0=284.,lat_0=41.,
                resolution ='h',area_thresh=1000.)

    x, y = m(lon[:], lat[:])

    # plot filled contours
    cf = m.contourf(x, y, ref[fh,0,:,:], cmap='Spectral_r', levels=levs, lw=0., vmin=rmi, vmax=rma)
    cbar = m.colorbar(cf, pad='7%')
    cb_la = ['{:.1f}'.format(ti) for ti in ticks]
    cbar.set_ticks(ticks)
    cbar.ax.set_yticklabels(cb_la, fontsize=18)
    cbar.set_label('dBZ', fontsize=22)

    # draw coastlines, meridians and parallels.
    m.drawcoastlines(linewidth=1.5, color='k')
    m.drawcountries(linewidth=1., color='k')
    m.drawcounties(linewidth=0.6, color='k')
    m.drawstates(linewidth=1., color='k')

    # set axis titles
    ax.set_title('Forecast hour: {:02d} - 1-km REF (shaded)'.format(fh),
                 x=0.0, y=1.02, horizontalalignment='left', fontsize=20)
    plt.suptitle('{}-UTC HRRR forecast - {}{}{}'.format(hh, yyyy, mm, dd), y=0.92, fontsize=26)
    #plt.tight_layout()
    imgname = 'ref_hrrr_{:02d}.png'.format(fh)
    plt.savefig(imgname)
    os.system('convert -trim {} {}'.format(imgname, imgname))
    plt.close()
Beispiel #18
0
def mapOne(lat, lon, projection = 'ortho', lat_0 = "", lon_0 = "",\
           llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180,\
           countries = True, counties = False, \
           rivers = False, states = False, background = "shadedrelief",\
           scale = 0.5, markersize = 50, marker = "ro", figsize = [4,4], \
           ax = None):
    """ Map one location on the globe
    
    Args:
        lat (float): a float number representing latitude
        lon (float): a float number representing longitude
        projection (string): the map projection. Refers to the Basemap
            documentation for a list of available projections. Only projections
            supporting setting the map center with a single lat/lon or with
            the coordinates of the rectangle are currently supported. 
            Default is to use a Robinson projection.
        lat_0, lon_0 (float): the center coordinates for the map. Default is
            mean latitude/longitude in the list. 
            If the chosen projection doesn't support it, Basemap will
            ignore the given values.
        llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon (float): The coordinates
            of the two opposite corners of the rectangle.
        countries (bool): Draws the countries border. Defaults is off (False). 
        counties (bool): Draws the USA counties. Default is off (False).
        rivers (bool): Draws the rivers. Default is off (False).
        states (bool): Draws the American and Australian states borders. 
            Default is off (False).
        background (string): Plots one of the following images on the map: 
            bluemarble, etopo, shadedrelief, or none (filled continents). 
            Default is none.
        scale (float): Useful to downgrade the original image resolution to
            speed up the process. Default is 0.5.
        markersize (int): The size of the marker.
        marker (str or list): color and type of marker. 
        figsize (list): the size for the figure
        ax: Return as axis instead of figure (useful to integrate plot into a subplot) 
    
    """
    if not lon_0:
        lon_0 = lon
    if not lat_0:
        lat_0 = lat
    
    if not ax:
        fig, ax = plt.subplots(figsize=figsize)
        
    map = Basemap(projection=projection, lat_0=lat_0, lon_0=lon_0,
                  llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,\
                  llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon)
    
    map.drawcoastlines()
    
    # Background
    if background == "shadedrelief":
        map.shadedrelief(scale = scale)
    elif background == "bluemarble":
        map.bluemarble(scale=scale)
    elif background == "etopo":
        map.etopo(scale=scale)
    elif background == "none":
        map.fillcontinents(color='0.9')
    else:
        sys.exit("Enter either 'shadedrelief','bluemarble','etopo',or'None'")
            
    #Other extra information
    if countries == True:
        map.drawcountries()
    if counties == True:
        map.drawcounties()
    if rivers == True:
        map.drawrivers()
    if states == True:
        map.drawrivers()
    
    #Plot the point
    X,Y = map(lon,lat)
    map.scatter(X,Y,s=markersize,facecolor=marker[0],marker=marker[1],zorder=10) 
    
    return ax
Beispiel #19
0
def create_basemap(corners=None, proj=None, resolution='l',
                   area_thresh=1000.,
                   meridians=True, parallels=True, dLon=2., dLat=2.,
                   coastlines=True, countries=True, states=False,
                   counties=False,
                   rivers=False, etopo=False, ax=None):
    """
    Create a basemap instance for plotting.

    Parameters
    ----------
    corners : float tuple
        Array of map corners
        [lowerLeftLon, lowerLeftLat, upperRightLon, upperRightLat].
        Default will find min max of arrays.
    proj : str
        Map projection to use.
    resolution : string
        Map resolution, 'l' or low res is default.
    area_thresh : float
        Minimum area threshold for basemap plot instance.
    meridians : bool
        Flag to turn on meridian (lonigitude) line plotting.
    parallels : bool
        Flag to turn on parallels (latitude) line plotting.
    dLon : float
        Spacing for meridians.
    dLat : float
        Spacing for parallels.
    coastlines : bool
        Flag to turn on basemap coastline plotting.
    countries : bool
        Flag to turn on basemap country plotting.
    states : bool
        Flag to turn on basemap state plotting.
    counties : bool
        Flag to turn on basemap county plotting.
    rivers : bool
        Flag to turn on basemap river plotting.
    etopo : bool
        Flag to turn on basemap etopo (topography) plotting.
    ax : Matplotlib axis instance
            Axis to plot. None will use the current axis.
    """
    # parse parameters
    ax = _parse_ax(ax)

    # Check inputs
    if corners is None:
        corners = [-180., -90., 180., 90.]

    if proj is None:
        proj = 'cea'

    # Create a basemap instance
    bm = Basemap(projection=proj, resolution=resolution,
                 area_thresh=area_thresh,
                 llcrnrlon=corners[0], urcrnrlon=corners[2],
                 llcrnrlat=corners[1], urcrnrlat=corners[3], ax=ax)

    # Check the customizations for the basemap
    if meridians:
        bm.drawmeridians(np.arange(corners[0], corners[
                         2], dLon), labels=[1, 0, 0, 1])
    if parallels:
        bm.drawparallels(np.arange(corners[1], corners[
                         3], dLat), labels=[1, 0, 0, 1])
    if countries:
        bm.drawcountries()
    if coastlines:
        bm.drawcoastlines()
    if states:
        bm.drawstates()
    if counties:
        bm.drawcounties()
    if rivers:
        bm.drawrivers()

    return bm
#Put the hrap coordinates into map coordinates
hx,hy = m(hraplon,hraplat)

#grid the data from the model onto the new hrap grid
imethod = 'linear'
hrapg = griddata(pts,flat,(hx,hy), method=imethod)

#Plot the hrap precip grid on map
#hs = m.contourf(hx,hy,hrapg,np.linspace(1,50,11),cmap=plt.cm.jet)

cb = m.colorbar(cs)  # draw colorbar
#add shaded releif as basemap
m.shadedrelief(scale=0.5)
#draw county lines on map
m.drawcounties(linewidth=1, linestyle='solid', color='k')

#Get map coordinates for grid corners and plot them
z,q = m(hlon,hlat)
m.scatter(z,q,color="blue",s=5)

i=99
#save the map
filename = 'image'+str(i)+imethod+'.png'
savefig(filename)

#Create and save the xmrg file
f = open('myfile','w')
xmrg = writeXMRG(hrapi[-1][0],hrapj[-1][0],hrapg)
f.write(xmrg) # python will convert \n to os.linesep
f.close() # you can omit in most cases as the destructor will call if
Beispiel #21
0
fig = plt.figure(1, figsize=[8, 8])
ax = fig.add_subplot(111)

## Draw Background basemap
bot_left_lat = 43.565
bot_left_lon = -116.276
top_right_lat = 44.222 + .05
top_right_lon = -115.29 - .05

## Map in cylindrical projection (data points may apear skewed)
m = Basemap(resolution='i',projection='cyl',\
    llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\
    urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,)
m.drawcoastlines()
m.drawcountries()
m.drawcounties(linewidth=2)
m.drawstates(linewidth=5)

# Brackground image
m.arcgisimage(service='NatGeo_World_Map', xpixels=1000, dpi=100, verbose=True)

# Fire perimiter
perimiter = '160816'
p4 = m.readshapefile(
    '/uufs/chpc.utah.edu/common/home/u0553130/fire_shape/perim_' + perimiter,
    'perim',
    drawbounds=False)

# fire August 6th, 2016
patches = []
for info, shape in zip(m.perim_info, m.perim):
time = nc.variables['time'][:]
t2 = nc.variables['p2t'][:] # 2 meter temperature
mslp = nc.variables['msl'][:] # mean sea level pressure
u = nc.variables['p10u'][:] # 10m u-component of winds
v = nc.variables['p10v'][:] # 10m v-component of winds


map = Basemap(projection='merc',llcrnrlon=-93.,llcrnrlat=35.,urcrnrlon=-73.,urcrnrlat=45.,resolution='i') # projection, lat/lon extents and resolution of polygons to draw
# resolutions: c - crude, l - low, i - intermediate, h - high, f - full


map.drawcoastlines()
map.drawstates()
map.drawcountries()
map.drawlsmask(land_color='Linen', ocean_color='#CCFFFF') # can use HTML names or codes for colors
map.drawcounties() # you can even add counties (and other shapefiles!)


parallels = np.arange(30,50,5.) # make latitude lines ever 5 degrees from 30N-50N
meridians = np.arange(-95,-70,5.) # make longitude lines every 5 degrees from 95W to 70W
map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)

lons,lats= np.meshgrid(lon-180,lat) # for this dataset, longitude is 0 through 360, so you need to subtract 180 to properly display on map
x,y = map(lons,lats)


clevs = np.arange(960,1040,4)
cs = map.contour(x,y,mslp[0,:,:]/100.,clevs,colors='blue',linewidths=1.)

Beispiel #23
0
cmin = 0; cmax = 8.; cint = 0.25; clevs = np.round(np.arange(cmin,cmax,cint),2)
nlevs = len(clevs) - 1; cmap = plt.get_cmap(name='bwr',lut=nlevs)
#plt.figure()
#plt.figure(figsize=(24,16))
#cornpmm, lon = shiftgrid(180., corrnpmm, lon, start=False)
#lon, lat = np.meshgrid(np.linspace(-180, 180, 360), np.linspace(-90, 90, 180))
#plt.figure(figsize=(18,18))
xlim = np.array([-140.,-60.]); ylim = np.array([10.,45.])
#parallels = np.arange(23.,35.,1.)
# labels = [left,right,top,bottom]
m = Basemap(projection='cyl',lon_0=np.mean(xlim),lat_0=np.mean(ylim),llcrnrlat=ylim[0],urcrnrlat=ylim[1],llcrnrlon=xlim[0],urcrnrlon=xlim[1],resolution='l')
m.drawcoastlines(); m.drawstates(), m.drawcountries(), m.drawstates(),  #m.drawparallels(parallels,labels=[True,True,True,True], size = 20) #m.fillcontinents(color='Black');m.drawparallels(np.arange(-180.,180.,30.), labels = [1,0,0,0]);m.drawmeridians(np.arange(-180,180,30),labels = [0,0,0,1])
#xCoord,yCoord = m(lat2, lon2)  ###Add lat-lon here
cs = m.contourf(lon,lat,anom_total.T,clevs,cmap='GnBu',extend='both') #plot lat, lon, and North Pacific SST Anomalies 
m.drawcounties()
#x2star,y2star = m(obs25['lon'],obs25['lat'])
#m.plot(x2star,y2star,'g*',markersize=2)

cbar = m.colorbar(cs,size='2%')
cbar.ax.set_ylabel('in',weight='bold',name='Calibri',size=14)
cticks = []
for i in clevs:
    cticks.append(int(i)) if i.is_integer() else cticks.append(i)
cbar.set_ticks(clevs[::4])
cbar.set_ticklabels(cticks[::4])
for i in cbar.ax.yaxis.get_ticklabels():
    i.set_family('Calibri')
    i.set_size(14)
plt.title('Sea surface temperature anomalies',name='Calibri',weight='bold',size=16)
'''
Beispiel #24
0
lon = np.array(posi["lon"][0:120])                        # 获取经度值
pop = np.array(posi["pop"][0:120],dtype=float)    # 获取人口数,转化为numpy浮点型

size=(pop/np.max(pop))*100    # 绘制散点图时图形的大小,如果之前pop不转换为浮点型会没有大小不一的效果

map = Basemap(projection='stere',
              lat_0=35, lon_0=110,
              llcrnrlon=82.33,
              llcrnrlat=3.01,
              urcrnrlon=138.16,
              urcrnrlat=53.123,resolution='l',area_thresh=10000,rsphere=6371200.)


map.drawcoastlines()
map.drawcountries()
map.drawcounties()
map.readshapefile(shapefile,'states',drawbounds=True)
map.drawmapboundary()


parallels = np.arange(0.,90,10.)
map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # 绘制纬线

meridians = np.arange(80.,140.,10.)
map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) # 绘制经线


x,y = map(lon,lat)

# map.scatter(x,y,edgecolors='r',facecolors='r',marker='*',s=320)
Beispiel #25
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

m = Basemap(projection='mill',
            llcrnrlat = -90,
            llcrnrlon = -180,
            urcrnrlat = 90,
            urcrnrlon = 180)

m.drawcoastlines()
m.drawcountries(linewidth=2)
m.drawstates(color='b')
m.drawcounties(color='darkred')

plt.title('Basemap Tutorial')
plt.show()
Beispiel #26
0
    def map_results(self):
        "save the nexrad locations to an array from the PyART library"
        locs = pyart.io.nexrad_common.NEXRAD_LOCATIONS
        "set up the figure for plotting"
        fig = plt.figure(figsize=(12, 8), dpi=100)
        ax = fig.add_subplot(111)
        "create a basemap for CONUS"
        m = Basemap(projection='lcc',
                    lon_0=-95,
                    lat_0=35.,
                    llcrnrlat=20,
                    urcrnrlat=50,
                    llcrnrlon=-120,
                    urcrnrlon=-60,
                    resolution='l')
        "draw the geography for the basemap"
        m.drawcoastlines(linewidth=1)
        m.drawcountries(linewidth=1)
        m.drawstates(linewidth=0.5)
        "plot a point and a label for each of the radar site locations within the CONUS domain"
        for key in locs:
            lon = locs[key]['lon']
            lat = locs[key]['lat']
            name = key
            if lon >= -120 and lon <= -60 and lat >= 20 and lat <= 50:
                m.scatter(lon, lat, marker='o', color='b', latlon=True)
                x, y = m(lon + 0.2, lat + 0.2)
                plt.text(x, y, name, color='k', fontsize=7)
        "create a figure title"
        fig.text(0.5,
                 0.92,
                 'CONUS NEXRAD locations',
                 horizontalalignment='center')
        plt.show()

        "base map has been fully developed at this time, move on to display data on base map"
        "select the radar site"
        site = get_results()
        "Here I want to fetch the site value that the user inputted from the previous function"

        "get the radar location (this is used to set up the basemap and plotting grid)"
        loc = pyart.io.nexrad_common.get_nexrad_location(site)
        lon0 = loc[1]
        lat0 = loc[0]
        "use boto to connect to the AWS nexrad holdings directory"
        s3conn = boto.connect_s3()
        bucket = s3conn.get_bucket('noaa-nexrad-level2')
        "create a datetime object for the current time in UTC and use the"
        "year, month, and day to drill down into the NEXRAD directory structure."
        start_time = get_results()
        """get the bucket list for the selected date
           Note: this returns a list of all of the radar sites with data for
           the selected date"""
        ls = bucket.list(prefix=start_time, delimiter=',')
        for key in ls:
            "only pull the data and save the arrays for the site we want"
            if site in key.name.split(',')[-2]:
                "set up the path to the NEXRAD files"
                path = start_time + site + ',' + site
                "grab the last file in the file list"
                fname = bucket.get_all_keys(prefix=path)[-1]
                "get the file"
                s3key = bucket.get_key(fname)
                "save a temporary file to the local host"
                localfile = tempfile.NamedTemporaryFile(delete=False)
                "write the contents of the NEXRAD file to the temporary file"
                s3key.get_contents_to_filename(localfile.name)
                "use the read_nexrad_archive function from PyART to read in NEXRAD file"
                radar = pyart.io.read_nexrad_archive(localfile.name)
                "get the date and time from the radar file for plot enhancement"
                time = radar.time['units'].split(' ')[-1].split('T')
                print(site + ': ' + time[0] + ' at ' + time[1])

                "set up the plotting grid for the data"
                display = pyart.graph.RadarMapDisplay(radar)
                x, y = display._get_x_y(0, True, None)

        # set up a 1x1 figure for plotting
        fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(9, 9), dpi=100)
        # set up a basemap with a lambert conformal projection centered
        # on the radar location, extending 1 degree in the meridional direction
        # and 1.5 degrees in the longitudinal in each direction away from the
        # center point.
        m = Basemap(projection='lcc',
                    lon_0=lon0,
                    lat_0=lat0,
                    llcrnrlat=lat0 - 1.25,
                    llcrnrlon=lon0 - 1.5,
                    urcrnrlat=lat0 + 1.25,
                    urcrnrlon=lon0 + 1.5,
                    resolution='h')

        # get the plotting grid into lat/lon coordinates
        x0, y0 = m(lon0, lat0)
        glons, glats = m((x0 + x * 1000.), (y0 + y * 1000.), inverse=True)
        # read in the lowest scan angle reflectivity field in the NEXRAD file
        refl = np.squeeze(radar.get_field(sweep=0, field_name='reflectivity'))
        # set up the plotting parameters (NWSReflectivity colormap, contour levels,
        # and colorbar tick labels)
        cmap = 'pyart_NWSRef'
        levs = np.linspace(0, 80, 41, endpoint=True)
        ticks = np.linspace(0, 80, 9, endpoint=True)
        label = 'Radar Reflectivity Factor ($\mathsf{dBZ}$)'
        # define the plot axis to the be axis defined above
        ax = axes
        # normalize the colormap based on the levels provided above
        norm = mpl.colors.BoundaryNorm(levs, 256)
        # create a colormesh of the reflectivity using with the plot settings defined above
        cs = m.pcolormesh(glons,
                          glats,
                          refl,
                          norm=norm,
                          cmap=cmap,
                          ax=ax,
                          latlon=True)
        # add geographic boundaries and lat/lon labels
        m.drawparallels(np.arange(20, 70, 0.5),
                        labels=[1, 0, 0, 0],
                        fontsize=12,
                        color='k',
                        ax=ax,
                        linewidth=0.001)
        m.drawmeridians(np.arange(-150, -50, 1),
                        labels=[0, 0, 1, 0],
                        fontsize=12,
                        color='k',
                        ax=ax,
                        linewidth=0.001)
        m.drawcounties(linewidth=0.5, color='gray', ax=ax)
        m.drawstates(linewidth=1.5, color='k', ax=ax)
        m.drawcoastlines(linewidth=1.5, color='k', ax=ax)
        # mark the radar location with a black dot
        m.scatter(lon0, lat0, marker='o', s=20, color='k', ax=ax, latlon=True)
        # add the colorbar axes and create the colorbar based on the settings above
        cax = fig.add_axes([0.075, 0.075, 0.85, 0.025])
        cbar = plt.colorbar(cs,
                            ticks=ticks,
                            norm=norm,
                            cax=cax,
                            orientation='horizontal')
        cbar.set_label(label, fontsize=12)
        cbar.ax.tick_params(labelsize=11)
        # add a title to the figure
        fig.text(0.5,
                 0.92,
                 site + ' (0.5$^{\circ}$) Reflectivity\n ' + time[0] + ' at ' +
                 time[1],
                 horizontalalignment='center',
                 fontsize=16)
        # display the figure
        plt.show()
Beispiel #27
0
def mapOne(lat, lon, projection = 'ortho', lat_0 = "", lon_0 = "",\
           llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180,\
           countries = True, counties = False, \
           rivers = False, states = False, background = "shadedrelief",\
           scale = 0.5, markersize = 50, marker = "ro", figsize = [4,4], \
           ax = None):
    """ Map one location on the globe
    
    Args:
        lat (float): a float number representing latitude
        lon (float): a float number representing longitude
        projection (string): the map projection. Refers to the Basemap
            documentation for a list of available projections. Only projections
            supporting setting the map center with a single lat/lon or with
            the coordinates of the rectangle are currently supported. 
            Default is to use a Robinson projection.
        lat_0, lon_0 (float): the center coordinates for the map. Default is
            mean latitude/longitude in the list. 
            If the chosen projection doesn't support it, Basemap will
            ignore the given values.
        llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon (float): The coordinates
            of the two opposite corners of the rectangle.
        countries (bool): Draws the countries border. Defaults is off (False). 
        counties (bool): Draws the USA counties. Default is off (False).
        rivers (bool): Draws the rivers. Default is off (False).
        states (bool): Draws the American and Australian states borders. 
            Default is off (False).
        background (string): Plots one of the following images on the map: 
            bluemarble, etopo, shadedrelief, or none (filled continents). 
            Default is none.
        scale (float): Useful to downgrade the original image resolution to
            speed up the process. Default is 0.5.
        markersize (int): The size of the marker.
        marker (str or list): color and type of marker. 
        figsize (list): the size for the figure
        ax: Return as axis instead of figure (useful to integrate plot into a subplot) 
    
    """
    if not lon_0:
        lon_0 = lon
    if not lat_0:
        lat_0 = lat

    if not ax:
        fig, ax = plt.subplots(figsize=figsize)

    map = Basemap(projection=projection, lat_0=lat_0, lon_0=lon_0,
                  llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,\
                  llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon)

    map.drawcoastlines()

    # Background
    if background == "shadedrelief":
        map.shadedrelief(scale=scale)
    elif background == "bluemarble":
        map.bluemarble(scale=scale)
    elif background == "etopo":
        map.etopo(scale=scale)
    elif background == "none":
        map.fillcontinents(color='0.9')
    else:
        sys.exit("Enter either 'shadedrelief','bluemarble','etopo',or'None'")

    #Other extra information
    if countries == True:
        map.drawcountries()
    if counties == True:
        map.drawcounties()
    if rivers == True:
        map.drawrivers()
    if states == True:
        map.drawrivers()

    #Plot the point
    X, Y = map(lon, lat)
    map.scatter(X,
                Y,
                s=markersize,
                facecolor=marker[0],
                marker=marker[1],
                zorder=10)

    return ax
Beispiel #28
0
def plotClusters(shapes, pts, box, show=8, title='', size=10):
    fig, ax = plt.subplots(figsize=(size, size))
    top9 = shapes.head(n=show).iloc[::-1]

    mapped = Basemap(projection='mill',
                     llcrnrlon=box[0],
                     llcrnrlat=box[1],
                     urcrnrlon=box[2],
                     urcrnrlat=box[3],
                     ax=ax)

    mapped.bluemarble(zorder=0, alpha=0.3)

    smallest = min(box[3] - box[1], box[2] - box[0])
    mapped.drawcoastlines(zorder=3, linewidth=0.7)
    if smallest < 5:
        mapped.drawcountries(zorder=3, linewidth=0.6)
        mapped.drawstates(zorder=3, linewidth=0.5)
        mapped.drawcounties(zorder=3, linewidth=0.2)
    else:
        mapped.drawcountries(zorder=3, linewidth=1.5)
        mapped.drawstates(zorder=3, linewidth=0.2)

    if smallest < 1.0:
        gridIncrement = 0.1
    if smallest < 2.5:
        gridIncrement = 0.5
    elif smallest < 5:
        gridIncrement = 1.0
    elif smallest < 10:
        gridIncrement = 2.5
    else:
        gridIncrement = 5.0

    parallels = np.arange(-90., 90., gridIncrement)
    mapped.drawparallels(parallels,
                         labels=[1, 0, 0, 0],
                         fontsize=10,
                         alpha=.75)
    meridians = np.arange(-180., 180., gridIncrement)
    mapped.drawmeridians(meridians,
                         labels=[0, 0, 0, 1],
                         fontsize=10,
                         alpha=.75)

    geoPrep = [
        shapely.ops.transform(mapped, poly) for poly in top9.geometry.tolist()
    ]
    top9.geometry = geoPrep

    top9.plot(column='count',
              ax=ax,
              cmap='YlOrRd',
              legend=True,
              scheme='QUANTILES',
              k=show,
              alpha=0.5,
              zorder=5)

    if show < 10:
        textArgs = {
            'facecolor': 'white',
            'alpha': 0.5,
            'pad': 4,
            'edgecolor': 'b'
        }
        leg = ax.get_legend()
        xs, ys = mapped(list(top9['centX']), list(top9['centY']))

        for i in reversed(range(show)):
            leg.get_texts()[top9.index[i]].set_text("%s: %s" %
                                                    (i, top9['count'][i]))
            plt.text(xs[i], ys[i], top9.index[i], bbox=textArgs, zorder=6)
        leg.set_bbox_to_anchor((1, 1))

    xs, ys = mapped(list(pts['lon']), list(pts['lat']))
    mapped.plot(xs,
                ys,
                'o',
                markersize=4,
                zorder=6,
                markerfacecolor='b',
                markeredgecolor="none",
                alpha=0.30)
    plt.title(title + "Cluster Spatial Distribution")

    return list(top9.index), ax
def DrawPointMap(companys,
                 stations,
                 picName='temp',
                 labelType='industry',
                 mode='single'):
    fig = plt.figure()
    ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])  #[left,bottom,width,height]
    #region 绘制底图
    map = Basemap(projection='mill',lat_0=29,lon_0=109, \
                  llcrnrlat=28 ,urcrnrlat=32.5,llcrnrlon=105,urcrnrlon=111, \
                  ax=ax1,rsphere=6371200.,resolution='h',area_thresh=10000)
    # shp_info = map.readshapefile('CHN_adm/CHN_adm3','states',drawbounds=False)
    shp_info = map.readshapefile('../CHN_adm/CHN_adm3',
                                 'states',
                                 drawbounds=False)
    for info, shp in zip(map.states_info, map.states):
        proid = info['NAME_1']
        if proid == 'Chongqing':
            poly = Polygon(shp,
                           facecolor='w',
                           edgecolor='k',
                           lw=1.0,
                           alpha=0.1)  #注意设置透明度alpha,否则点会被地图覆盖
            ax1.add_patch(poly)

    parallels = np.arange(28.0, 41.0, 0.1)
    #map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) #parallels
    meridians = np.arange(105.0, 110.0, 0.1)
    #map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) #meridians
    map.drawmapboundary()  #边界线
    #map.fillcontinents()
    map.drawstates()
    #map.drawcoastlines()  #海岸线
    map.drawcountries()
    map.drawcounties()
    #endregion

    #region 初始化颜色字典
    # 行业分类颜色字典
    IndustryColorDic = {
        1: "#b71c1c",
        2: "#f48fb1",
        3: "#6a1b9a",
        4: "#311b92",
        5: "#536dfe",
        6: "#1a237e",
        7: "#4fc3f7",
        8: "#18ffff",
        9: "#64ffda",
        10: "#4caf50",
        11: "#b2ff59",
        12: "#9e9d24",
        13: "#ffff00",
        14: "#ffb300",
        15: "#f4511e",
        16: "#6d4c41",
        17: "#616161",
        18: "#607d8b",
    }
    # 聚类分类颜色字典
    ClusterColorDic = {
        0: "#DC143C",  # 猩红
        1: "#0000FF",  # 纯蓝
        2: "#008000",  # 纯绿
        3: "#FFFF00",  # 纯黄
        4: "#536dfe",
        5: "#1a237e",
        6: "#4fc3f7",
        7: "#18ffff",
        8: "#64ffda",
        9: "#4caf50",
        10: "#b2ff59",
        11: "#9e9d24",
        12: "#ffff00",
        13: "#ffb300",
        14: "#f4511e",
        15: "#6d4c41",
        16: "#616161",
        17: "#607d8b"
    }
    #endregion

    #region 遍历所有公司信息
    temp_lat_list = []
    temp_lng_list = []
    temp_name_list = []
    for model in companys:
        #生成单行业图片
        # if(model.industry_label not in (7,)):
        #     continue
        temp_lat_list.append(model.lat)
        temp_lng_list.append(model.lng)
        temp_name_list.append(model.InterID)

    lat = np.array(temp_lat_list, dtype=float)  #获取经纬度坐标
    lon = np.array(temp_lng_list, dtype=float)
    x, y = map(lon, lat)
    map.scatter(x, y, s=10, marker='.', edgecolors='none',
                color='r')  #要标记的点的坐标、大小及颜色
    #endregion

    #region 公司位置标记文字
    # for i in range(len(temp_name_list)):
    #     temp_x=float(temp_lng_list[i])
    #     temp_y=float(temp_lat_list[i])
    #     temp_id = temp_name_list[i]
    #     x,y = map(temp_x,temp_y)
    #     plt.text(x,y,temp_id,fontsize=0.00005,ha='left',va='center',color='k')
    #endregion

    #region 遍历所有地铁站信息
    temp_sta_lat_list = []
    temp_sta_lng_list = []
    temp_staID_list = []
    for model in stations:
        #if model.StaType in (1,2):continue
        temp_sta_lat_list.append(model.lat)
        temp_sta_lng_list.append(model.lng)
        temp_staID_list.append(model.StationID)

    lat_sta = np.array(temp_sta_lat_list, dtype=float)  #获取经纬度坐标
    lon_sta = np.array(temp_sta_lng_list, dtype=float)
    ID_sta = np.array(temp_staID_list, dtype=str)

    m, n = map(lon_sta, lat_sta)
    map.scatter(m, n, s=1, marker='.', edgecolor='b',
                color='w')  # 要标记的点的坐标、大小及颜色
    #endregion

    #size = (val-np.min(val)+0.05)*800#对点的数值作离散化,使得大小的显示明显
    #map.scatter(x, y,s=size,marker='.',edgecolors='none',color = 'r') #要标记的点的坐标、大小及颜色
    # for i in range(0,3):
    #     plt.text(x[i]+5000,y[i]+5000,str(val[i]))

    #region 标记文字
    # for i in range(len(temp_staID_list)):
    #     temp_x=float(temp_sta_lng_list[i])
    #     temp_y=float(temp_sta_lat_list[i])
    #     temp_id = temp_staID_list[i]
    #     x,y = map(temp_x,temp_y)
    #     plt.text(x,y,temp_id,fontsize=0.00005,ha='left',va='center',color='k')
    #endregion

    #region 生成图片
    figName = picName
    plt.title(figName)  #标题
    plt.savefig('../result/' + figName + '.png', dpi=1000,
                bbox_inches='tight')  #文件命名为Chongqing.png存储
    plt.close()
    #plt.show()
    print('picture drawing finished')
Beispiel #30
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
#Actual Map, Projects Values that square  around western US
m=Basemap(projection='mill',llcrnrlat=31,urcrnrlat=43,\
			llcrnrlon=-130,urcrnrlon=-109,resolution='l')


#Coast lines			
m.drawcoastlines()
#continent filled with light beige using hexidecimal, lake is cyan, layered below county lines
m.fillcontinents(color='#ffffb3',lake_color='c',zorder=0)
m.drawcounties(linewidth=2,color='r',zorder=1)
m.drawstates(color='k')
#Establishes Outer Border of states for better Asthetic Look
m.drawmapboundary(fill_color='aqua')
#Shade relif gives better proccessing and asthetics
m.shadedrelief()
plt.title('California Presidential Candidate Support')

#900xx Area Code 
NineHundredlat, NineHundredlon= 34.05, -118.25
xpt, ypt = m (NineHundredlon, NineHundredlat)
NineHundredlonpt, NineHundredlat = m(xpt, ypt, inverse=True)
m.plot(xpt, ypt, '*', markersize=20)
#902xx Area Code
NineHundredTwolat, NineHundredTwolon= 33.99, -118.1
xpt, ypt = m (NineHundredTwolon, NineHundredTwolat)
NineHundredTwolonpt, NineHundredTwolat = m(xpt, ypt, inverse=True)
m.plot(xpt, ypt, '*', markersize=20)
plt.show()
Beispiel #31
0
        pickle.dump(lats, output, -1)
        pickle.dump(interp, output, -1)
else:
    with open('plot_05_08_16.pkl', 'rb') as input:
        fig = plt.figure()
        ax=plt.gca()
        m = pickle.load(input)
        topodat = pickle.load(input)
        lons = pickle.load(input)
        lats = pickle.load(input)

# lafayette
plt.plot(*m(-86.8786,40.4172), marker='d')

m.drawstates()
m.plot(lon, lat, 'r-', latlon=True)

m.ax = ax
m.drawstates(linewidth=0.1, color="#A7A9AC")
m.drawrivers(linewidth=1.5, color="#7299C6")
m.fillcontinents(color='white', lake_color='#7299C6')
m.drawcoastlines(linewidth=0.1, color="#A7A9AC")
m.drawcounties(linewidth=0.1, color="#A7A9AC")

ax.contour(x, y, topodat, 15, cmap=cm.terrain,  vmin=-800.0, vmax=2000.,
           linewidth=0.3)

ax.axis("off")

plt.show()
Beispiel #32
0
def mapAll(lat, lon, criteria, projection = 'robin', lat_0 = "", lon_0 = "",\
           llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, \
           countries = False, counties = False, rivers = False, states = False,\
           figsize = [10,4], ax = None,\
           background = 'none', scale = 0.5, palette="", markersize = 50):
    """ Map the location of all lat/lon according to some criteria 
    
    Map the location of all lat/lon according to some criteria. The choice of 
    plotting color/marker is passed through palette according to unique 
    criteria (e.g., record name, archive type, proxy observation type).
    
    Args:
        lat (list): a list of latitude.
        lon (list): a list of longitude.
        criteria (list): a list of criteria for plotting purposes. For instance,
            a map by the types of archive present in the dataset or proxy
            observations.
        projection (string): the map projection. Refers to the Basemap
            documentation for a list of available projections. Only projections
            supporting setting the map center with a single lat/lon or with
            the coordinates of the rectangle are currently supported. 
            Default is to use a Robinson projection.
        lat_0, lon_0 (float): the center coordinates for the map. Default is
            mean latitude/longitude in the list. 
            If the chosen projection doesn't support it, Basemap will
            ignore the given values.
        llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon (float): The coordinates
            of the two opposite corners of the rectangle.
        countries (bool): Draws the countries border. Defaults is off (False). 
        counties (bool): Draws the USA counties. Default is off (False).
        rivers (bool): Draws the rivers. Default is off (False).
        states (bool): Draws the American and Australian states borders. 
            Default is off (False).
        background (string): Plots one of the following images on the map: 
            bluemarble, etopo, shadedrelief, or none (filled continents). 
            Default is none.
        scale (float): Useful to downgrade the original image resolution to
            speed up the process. Default is 0.5.
        palette (dict): A dictionary of plotting color/marker by criteria. The
            keys should correspond to ***unique*** criteria with a list of 
            associated values. The list should be in the format 
            ['color', 'marker'].
        markersize (int): The size of the marker.
        figsize (list): the size for the figure
        ax: Return as axis instead of figure (useful to integrate plot into a subplot) 
        
    Returns:
        The figure       
    """
    #Check that the lists have the same length and convert to numpy arrays
    if len(lat)!=len(lon) or len(lat)!=len(criteria) or len(lon)!=len(criteria):
        sys.exit("Latitude, Longitude, and criteria list must be the same" +\
                 "length")
    
    # Grab the center latitude/longitude 
    if not lat_0:
        lat_0 = np.mean(np.array(lat))
    
    if not lon_0:
        lon_0 = np.mean(np.array(lon))
        
    # If palette is not given, then make a random one.
    if not palette:
        marker_list = ['o','v','^','<','>','8','s','p','*','h','D']
        color_list = ['#FFD600','#FF8B00','k','#86CDFA','#00BEFF','#4169E0',\
                 '#8A4513','r','#FF1492','#32CC32','#FFD600','#2F4F4F']
        # select at random for unique entries in criteria
        marker = [random.choice(marker_list) for _ in range(len(set(criteria)))]
        color = [random.choice(color_list) for _ in range(len(set(criteria)))]
        crit_unique = [crit for crit in set(criteria)]
        #initialize the palette
        palette = {crit_unique[0]:[color[0],marker[0]]}
        for i in range(len(crit_unique)):
            d1 = {crit_unique[i]:[color[i],marker[i]]}
            palette.update(d1)
            
    #Make the figure
    if not ax:
        fig, ax = plt.subplots(figsize=figsize)
        
    map = Basemap(projection = projection, lat_0 = lat_0, lon_0 = lon_0,\
                  llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,\
                  llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon)
    map.drawcoastlines()
    
    # Background
    if background == "shadedrelief":
        map.shadedrelief(scale = scale)
    elif background == "bluemarble":
        map.bluemarble(scale=scale)
    elif background == "etopo":
        map.etopo(scale=scale)
    elif background == "none":
        map.fillcontinents(color='0.9', lake_color = 'w')
    else:
        sys.exit("Enter either 'shadedrelief','bluemarble','etopo',or'None'")
            
    #Other extra information
    if countries == True:
        map.drawcountries()
    if counties == True:
        map.drawcounties()
    if rivers == True:
        map.drawrivers()
    if states == True:
        map.drawrivers()
    
    # Get the indexes by criteria
    for crit in set(criteria):
        # Grab the indices with same criteria
        index = [i for i,x in enumerate(criteria) if x == crit]
        X,Y =map(np.array(lon)[index],np.array(lat)[index])
        map.scatter(X,Y,
                    s= markersize,
                    facecolor = palette[crit][0],
                    marker = palette[crit][1],
                    zorder = 10,
                    label = crit)
    plt.legend(loc = 'center', bbox_to_anchor=(1.25,0.5),scatterpoints = 1,
               frameon = False, fontsize = 8, markerscale = 0.7)
    
    return ax    
Beispiel #33
0
def plotClusters(shapes,pts,box,show=8,title='',size=10):
    fig,ax = plt.subplots(figsize=(size,size))
    top9 = shapes.head(n=show).iloc[::-1]

    mapped = Basemap(projection='mill', 
                     llcrnrlon=box[0],
                     llcrnrlat=box[1],
                     urcrnrlon=box[2],
                     urcrnrlat=box[3],
                     ax=ax)

    mapped.bluemarble(zorder=0,alpha=0.3)
    
    smallest = min(box[3]-box[1],box[2]-box[0])
    mapped.drawcoastlines(zorder=3,linewidth = 0.7)
    if smallest < 5:
        mapped.drawcountries(zorder=3,linewidth = 0.6)
        mapped.drawstates(zorder=3, linewidth = 0.5)
        mapped.drawcounties(zorder=3,linewidth = 0.2)
    else:
        mapped.drawcountries(zorder=3,linewidth = 1.5)
        mapped.drawstates(zorder=3, linewidth = 0.2)
    
    if smallest < 1.0:
        gridIncrement = 0.1
    if smallest < 2.5:
        gridIncrement = 0.5
    elif smallest < 5:
        gridIncrement = 1.0
    elif smallest < 10:
        gridIncrement = 2.5
    else:
        gridIncrement = 5.0
    
    parallels = np.arange(-90.,90.,gridIncrement)
    mapped.drawparallels(parallels,labels=[1,0,0,0],fontsize=10, alpha = .75)
    meridians = np.arange(-180.,180.,gridIncrement)
    mapped.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10, alpha = .75)

    geoPrep = [shapely.ops.transform(mapped, poly) for poly in top9.geometry.tolist()]
    top9.geometry = geoPrep
    
    top9.plot(column='count',
              ax=ax,
              cmap='YlOrRd',
              legend=True,
              scheme='QUANTILES',
              k=show,
              alpha=0.5,
              zorder=5)
    
    if show < 10:
        textArgs = {'facecolor':'white', 'alpha':0.5, 'pad':4, 'edgecolor':'b'}
        leg = ax.get_legend()
        xs, ys = mapped(list(top9['centX']),list(top9['centY']))

        for i in reversed(range(show)):
            leg.get_texts()[top9.index[i]].set_text("%s: %s" % (i,top9['count'][i]))
            plt.text(xs[i],ys[i],top9.index[i],bbox=textArgs,zorder=6)
        leg.set_bbox_to_anchor((1, 1))
    
    xs, ys = mapped(list(pts['lon']),list(pts['lat']))
    mapped.plot(xs, ys, 'o', markersize=4,zorder=6, markerfacecolor='b',markeredgecolor="none", alpha=0.30)
    plt.title(title + "Cluster Spatial Distribution")

    return list(top9.index), ax
Beispiel #34
0
def drawing(data_list):
    plt.figure(figsize=(10, 5))

    m = Basemap(projection='lcc',
                lat_0=40,
                lon_0=-80,
                llcrnrlat=35,
                urcrnrlat=45,
                llcrnrlon=-90,
                urcrnrlon=-73,
                rsphere=6371200.,
                resolution='l',
                area_thresh=10000)
    m.drawcounties()
    m.drawstates()
    m.drawcoastlines()
    m.drawmapboundary()
    parallels = np.arange(0, 90, 10.)

    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)

    meridians = np.arange(-110., -60., 10.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)

    county_FIPS_list = list()
    colors = {}
    patches = []
    index_list = list()
    cmap = plt.cm.YlOrRd
    vmin_ele = min(data_list, key=lambda ele: ele.MOI)
    vmin = vmin_ele.MOI
    vmax_ele = max(data_list, key=lambda ele: ele.MOI)
    vmax = vmax_ele.MOI

    index = 0
    for county in m.counties_info:
        if county['STATE_FIPS'] in {'21', '39', '42', '51', '54'}:
            county_FIPS = county['FIPS']
            for i in data_list:
                if str(i.FIPS) == county_FIPS:
                    moi = i.MOI
                    colors[county_FIPS] = cmap(
                        np.sqrt((moi - vmin) / (vmax - vmin)))
                    county_FIPS_list.append(county_FIPS)
                    index_list.append(index)
        index += 1
    ax = plt.gca()
    index = 0

    for nshape, seg in enumerate(m.counties):
        if nshape in index_list:
            color = rgb2hex(colors[county_FIPS_list[index]])
            poly = Polygon(seg, facecolor=color, edgecolor=color)
            index += 1
            patches.append(poly)
            ax.add_patch(poly)

    # add colorbar
    colors1 = [i[1] for i in colors.values()]
    colorVotes = plt.cm.YlOrRd
    p = PatchCollection(patches, cmap=colorVotes)
    p.set_array(np.array(colors1))
    pylab.colorbar(p)

    plt.show()
Beispiel #35
0
b = Basemap(projection='merc', fix_aspect=False,
            urcrnrlat=NORTH,
            llcrnrlat=SOUTH,
            urcrnrlon=EAST,
            llcrnrlon=WEST,
            resolution='i', ax=ax[0])
cmap = plt.get_cmap('jet')
cmap.set_under('white')
clevs = [0.01, 0.25, 0.5, 0.75, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
norm = mpcolors.BoundaryNorm(clevs, cmap.N)
r = b.imshow(np.flipud(total) / 25.4, aspect='auto', norm=norm,
             cmap=cmap, interpolation='nearest',
             extent=(WEST, EAST, SOUTH, NORTH))
b.drawstates(linewidth=1., color='k')
b.drawcounties(color='k')
b.drawcountries(color='k')
plt.colorbar(r, ax=ax[0])
ax[0].set_title(("NOAA MRMS Q3 ::15 Apr 12:00 AM to 18 Apr 7:00 AM\n"
                 "Total Precipitation [inches]"))

# -------------------------------------------------------------------

cmap = plt.get_cmap('jet')
cmap.set_under('white')
clevs = np.arange(0.01, 0.14, 0.01)
norm = mpcolors.BoundaryNorm(clevs, cmap.N)
r = ax[1].imshow(res / 25.4, norm=norm, cmap=cmap,
                 aspect='auto', interpolation='nearest',
                 extent=(WEST, EAST, t, 0))
plt.colorbar(r, ax=ax[1])
Beispiel #36
0
# Lambert Conformal map of Vermont
# LL: 42.611417, -73.672795
# UR: 45.086798, -71.244816
# Center: 43.8491075, -72.4588055
geoMap = Basemap(llcrnrlon=-73.672795, llcrnrlat=42.611417, urcrnrlon=-71.244816,
urcrnrlat=45.086798, projection='lcc', lat_0=43.8491075, lon_0=-72.4588055,
resolution='i', area_thresh=100)
# Draw the coastlines of continental area
geoMap.drawcoastlines()
# Draw country boundaries
geoMap.drawcountries(linewidth=2)
# Draw states boundaries (America only)
geoMap.drawstates(linewidth=2)
# Draw State county Boundaries
geoMap.drawcounties(linewidth=1)
# Fill the background (the oceans)
geoMap.drawmapboundary(fill_color='aqua')
# Fill the continental area
geoMap.fillcontinents(color='#70B870',lake_color='aqua')

# For Loop to add user locations.
state2LatLong = [['VT',44.0407,-72.7093]]

for i in range(len(state2LatLong)):
    # Get the x,y coordinate for the geoplot. For whatever reason, it's Long / Lat instead
    # of the standard Lat / Long.
    x, y = geoMap(state2LatLong[i][2],state2LatLong[i][1])
    plt.plot(x,y,'ro')
    plt.text(x+10000,y+10000,state2LatLong[i][0], bbox=dict(facecolor='yellow',alpha=0.5))
fig = plt.figure(figsize=(4, 2))
m = Basemap(projection='merc',
            llcrnrlon=-78.5079,
            llcrnrlat=38.00905,
            urcrnrlon=-75.6454,
            urcrnrlat=39.91155,
            resolution='h')
ny = dura.shape[0]
nx = dura.shape[1]
lons, lats = m.makegrid(nx, ny)  # get lat/lons of ny by nx evenly space grid.
x, y = m(lons, lats)
mdata = maskoceans(lons, lats, dura)

m.drawcoastlines()
m.drawcounties(linewidth=0.4)

parallels = np.arange(0., 90, 0.5)
m.drawparallels(parallels,
                labels=[1, 0, 0, 0],
                dashes=[2, 900],
                fontsize=10,
                linewidth=0.4)
meridians = np.arange(180., 360., 1)
m.drawmeridians(meridians,
                labels=[0, 0, 0, 1],
                dashes=[2, 900],
                fontsize=10,
                linewidth=0.4)

cMAP = ListedColormap([
class CountyMap(object):
    """ A class that encompasses an interactive visualization of some
        of the counties in the Northeast """

    def __init__(self):
        """ Initialize the map by creating the Basemap object,
            drawing the county outlines, filling in some of the
            counties with various colors, and plotting a dot
            on Olin College. """
        self.m = Basemap(projection='mill',
                         llcrnrlat=40,
                         llcrnrlon=-75,
                         urcrnrlat=43,
                         urcrnrlon=-69.5,
                         resolution='c')
        self.last_hover = None
        self.counties = self.m.drawcounties(linewidth=1)
        x, y = self.get_x_y(-71.2639, 42.2935)
        self.m.plot(x, y, 'k.')
        self.dots()
        plt.gcf().canvas.mpl_connect('motion_notify_event', self.on_hover)
        plt.ion()
        plt.show()
        self.text = None

    def get_x_y(self, lon, lat):
        """ Returns the x, y coordinate of a given longitude and lattitude """
        return self.m(*np.asarray([lon, lat]))

    def get_lon_lat(self, x, y):
        """ Returns longitude, lattitude for a given x, y plot coordinate """
        return self.m(*np.asarray([x, y]), inverse=True)

    def on_hover(self, event):
        """ Handle matplotlib mouse events.  All we do currently is save
            the coordinates of the mouse for later processing """
        if event.xdata and event.ydata:
            self.last_hover = (event.xdata, event.ydata)

    def run(self):
        """ The main run loop of the program.  The loop continuously updates
            the plot using the last registered position of the mouse.
            The mouse position is also used to compute which county the
            user is currently hovering over.  Based on this determination
            the text displayed to the user is updated.
        """
        # cache the paths for faster performance in the loop
        paths = self.counties.properties()['paths']
        # while True:
        #     if self.last_hover:
        #         lon, lat = self.get_lon_lat(self.last_hover[0],
        #                                     self.last_hover[1])
        #         new_text = "Lattitude %f, \nLongitude %f" % (lat, lon)

        #         for i, path in enumerate(paths):
        #             if (path.contains_point(self.last_hover)):
        #                 new_text += "\n" + self.m.counties_info[i]['NAME']
        #                 break
        #         if not self.text:
        #             self.text = plt.gca().text(self.last_hover[0],
        #                                        self.last_hover[1],
        #                                        new_text,
        #                                        style='italic',
        #                                        bbox={'facecolor': 'red',
        #                                              'alpha': 0.5,
        #                                              'pad': 10})
        #         else:
        #             self.text.set_x(self.last_hover[0])
        #             self.text.set_y(self.last_hover[1])
        #             self.text.set_text(new_text)

        #     # make sure that the plot is redrawn
        #     plt.gcf().canvas.update()
        #     plt.gcf().canvas.flush_events()
    def dots(self):
    # olin, university of rhode island,bard,northeastern,risd,nyu,tufts
        size = [350, 6694, 6309, 27728, 8000, 20000, 5000]
        lats = [42.293167,41.485338,42.020389,42.339806,41.825842,40.730104,42.407484]
        lons = [-71.265859,-71.531236,-73.912248,-71.091365,-71.40993,-74.002028,-71.121217]
        x,y = self.m(lons, lats)
        for i in range(len(size)):
            if size[i] <= 5000:
                self.m.plot(x[i], y[i], 'go', markersize=size[i]/1000)
            elif size[i] >= 10000:
                self.m.plot(x[i], y[i], 'ro', markersize=size[i]/1000)
            else:
                self.m.plot(x[i], y[i], 'bo', markersize=size[i]/1000)
        plt.show()
def plot_map():
    global earth_radius_meters
    # setup Lambert Conformal basemap.
    # set resolution=None to skip processing of boundary datasets.
    m = Basemap(width=600000,
                height=450000,
                projection='lcc',
                lat_0=station_lat,
                lon_0=station_lon,
                resolution='c')
    m.drawmapboundary(zorder=-2)
    m.fillcontinents(zorder=-1)
    m.drawcoastlines(linewidth=0.5)
    m.drawstates()
    m.drawcounties()
    m.drawrivers()
    m.scatter(station_lon, station_lat, latlon=True)
    elevation_angle = f.variables['elevationV_HI'][0]
    elevation_angle = np.mean(elevation_angle)
    rounded_elevation_angle = round(elevation_angle, 2)
    data_at_elevation = f.variables['RadialVelocity_HI'][0]
    data_at_elevation = np.array(data_at_elevation)
    data_at_elevation[data_at_elevation == 0] = np.nan
    data_at_elevation[data_at_elevation == 1] = np.nan
    # lowest_angle = (lowest_angle + f.variables['RadialVelocity'].add_offset) * f.variables['RadialVelocity'].scale_factor
    data_at_elevation = data_at_elevation / f.variables[
        'RadialVelocity_HI'].scale_factor
    # data_at_elevation = data_at_elevation.transpose()
    gates = np.array(f.variables['distanceV_HI'])
    gates = gates
    angles = np.array(f.variables['azimuthV_HI'][0])
    min_index = np.argmin(angles)
    angles = np.roll(angles, min_index * -1)
    data_at_elevation = np.roll(data_at_elevation, min_index * -1, axis=1)
    radar_elevation_above_sea_level = getattr(f, 'StationElevationInMeters')
    radar_tower_height = 0
    earth_radius_meters = 6378137
    lon_points = []
    lat_points = []
    distances = []
    for g in range(len(gates)):
        b = (earth_radius_meters + radar_tower_height)
        c = gates[g]
        a = math.sqrt(b**2 + c**2 -
                      (2 * b * c *
                       math.cos(math.radians(90 + elevation_angle))))
        h = a - earth_radius_meters
        # heights_at_angle.append(h)

        theta_at_core = math.asin(
            (gates[g] * math.sin(math.radians(90 + elevation_angle)) / a))
        distance = theta_at_core * earth_radius_meters

        distances.append(distance)
    distances = np.array(distances)
    data = []
    count = 0
    for theta in angles[::5]:
        for distance in distances[::10]:
            results = displace(station_lat, station_lon, theta, distance)
            lat = results[0]
            lon = results[1]
            lat_points.append(lat)
            lon_points.append(lon)
            angle_idx = angles.tolist().index(theta)
            distance_idx = distances.tolist().index(distance)
            data.append((data_at_elevation[angle_idx][distance_idx], lat, lon))
            count += 1
    print(count)
    data = np.array(data)
    # fig, ax = plt.subplots()
    # im = ax.pcolormesh(angles[:], gates[:], data_at_elevation[:])  # if you want contour plot
    # title = "{:.2f}".format(rounded_elevation_angle) + " degrees" + " / HR"
    # ax.set_title(title)
    # ax.set_xlabel('Azimuth angle in degrees: 0 = true north, 90 = east')
    # ax.set_ylabel('Distance from radar in km')
    # bar = fig.colorbar(im, ticks=range(-70, 75, 5), orientation='horizontal')
    # bar.set_label('Radial velocity in m/s')
    lon_points = np.array(lon_points[::])
    lon_points_s = np.sort(lon_points)
    lat_points = np.array(lat_points[::])
    lat_points_s = np.sort(lat_points)

    shaped_data = []
    for y in lat_points:
        row = []
        for x in lon_points:
            point = np.nan
            for d in data:
                if d[1] == y and d[2] == x:
                    point = d[0]
            row.append(point)
        shaped_data.append(row)
    shaped_data = np.array(shaped_data)

    X, Y = np.meshgrid(lon_points, lat_points)
    # plt.pcolormesh(X,Y,Z)
    # plt.show()
    m.pcolormesh(X, Y, shaped_data, latlon=True)
    m.scatter(lon_points, lat_points, latlon=True)
    plt.show()
Beispiel #40
0
fig = plt.figure(figsize=(27,30))

ax = fig.add_subplot(1,1,1)

m = Basemap(projection='lcc', lat_0 = lat_0, lon_0 = lon_0, lat_1 = lat_1,
      llcrnrlon = llcrnrlon, llcrnrlat = llcrnrlat,
      urcrnrlat = urcrnrlat, urcrnrlon = urcrnrlon,
      area_thresh = 1000., rsphere = rsphere, resolution='l')
#grid_lon, grid_lat = m.makegrid(len(x),len(y))
#print grid_lon, grid_lat

x = (m.llcrnrx - x.min()) + x
y = (m.llcrnry - y.min()) + y

cmap = radar_colormap()
cmap.set_bad('k')
norm = mpl.colors.Normalize(vmin=-35, vmax=80)
ax.text(0.5, .95, title, transform=plt.gca().transAxes,fontsize=16, horizontalalignment='center', bbox=dict(facecolor='white', alpha=0.9, boxstyle='round'))                                                     
#cax = m.pcolormesh(x, y, data, cmap=cmap, norm=norm)
cax = m.imshow(data, extent = (x.min(), x.max(), y.min(), y.max()), cmap=cmap, norm=norm, origin="upper")
m.drawcoastlines(color='#FFFFFF')
m.drawstates(color='#FFFFFF')
m.drawcountries(color='#FFFFFF')
m.drawcounties(color='#FFFFFF', linewidth=0.09)
cbar = m.colorbar(cax)
plt.tight_layout()
plt.savefig(path_to_imgs + 'radar_0.png', bbox_inches='tight')



Beispiel #41
0
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm

%matplotlib inline

map = Basemap(projection='stere',lat_0=31,lon_0=121,
	llcrnrlat=30,urcrnrlat=32,
	llcrnrlon=120,urcrnrlon=122,
	rsphere=6371200.,resolution='h',area_thresh=10)
map.drawmapboundary() # 绘制边界
map.drawstates() # 绘制州
map.drawcoastlines() # 绘制海岸线
map.drawcountries() # 绘制国家
map.drawcounties() # 绘制县

parallels = np.arange(30.,32.,.5)
map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # 绘制纬线
meridians = np.arange(120.,122.,.5)
map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) # 绘制经线
lat = df_loc_group[“lat”] # 获取纬度值
lon = df_loc_group[“lng”] # 获取经度值
price = df_loc_group[“price”] # 获取平均房价
cm = plt.cm.get_cmap('Reds')
z = (price - price.min())/(price.max() - price.min()) # 绘制散点图时散点颜色深浅表示均价高低,颜色越深价格越高

lon = np.array(lon)
lat = np.array(lat)
x,y = map(lon, lat)
sc = map.scatter(x,y,marker=',',c=z,s=0.1,cmap=cm)
Beispiel #42
0
def mapSubject(dataset,subject,box='tight',level='auto',
               longest=20,call='default',highlight=False,
               heatmap=True, mark = 'r', cmap='YlOrRd',
               show = True, offset = 0, subtitle = '', geobox = 'null',
	       important = 'null',background = 'none'):

    if call == 'animate':
        plt.clf()
    else:
        fig = plt.figure(figsize=(9,9))
    
    if geobox == 'null' or (type(box) is str and type(geobox) is str):
    	box = fixBox(dataset,box)
    else:
        box = geobox
    	
    lats, lons, times = getData(dataset,offset)
    
    mapped = Basemap(projection='mill', 
                     llcrnrlon=box['lon1'],
                     llcrnrlat=box['lat1'],
                     urcrnrlon=box['lon2'],
                     urcrnrlat=box['lat2'])

    mapOpacity = 0.75
    if background == 'etopo':
	mapped.etopo(zorder=0, alpha=mapOpacity)
    elif background == 'shaded relief':
	mapped.shadedrelief(zorder=0, alpha=mapOpacity)
    elif background == 'blue marble':
        mapped.bluemarble(zorder=0, alpha=mapOpacity)
    elif '/' in background or '.' in background:
        try:
            mapped.warpimage(image='maps/'+background, scale=None, zorder=0, alpha=mapOpacity)
        except:
            mapped.warpimage(image=background, scale=None, zorder=0, alpha=mapOpacity)
    else:
	background = 'null'
	
    smallest = min(box['lat2']-box['lat1'],box['lon2']-box['lon1'])

    mapped.drawcoastlines(zorder=3)
    
    if smallest < 5:
        mapped.drawcountries(zorder=3,linewidth = 3)
        mapped.drawstates(zorder=3, linewidth = 2)
        mapped.drawcounties(zorder=3,linewidth = 1)
    else:
        mapped.drawcountries(zorder=3,linewidth = 2)
        mapped.drawstates(zorder=3, linewidth = 1)
    
    if heatmap:
        # ######################################################################
        # http://stackoverflow.com/questions/11507575/basemap-and-density-plots)
        density, lon_bins, lat_bins = getDensity(box,lats,lons,longest)
        lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bins, lat_bins)
        xs, ys = mapped(lon_bins_2d, lat_bins_2d) # will be plotted using pcolormesh
        # ######################################################################
        
        if level == 'auto':
            level = np.amax(density)

	density = fixDensity(density,xs,ys)
	
  	if background == 'null':
        	plt.pcolormesh(xs, ys, density, cmap = cmap,zorder=2, alpha = 1, vmin =1)
	else:
		extent = (xs[0][0],xs[0][-1],ys[0][0],ys[-1][0]) 
		colorized = mapColors(density,level,cmap)
		colorized = mapTransparency(density,colorized,level)
		plt.imshow(colorized, extent=extent,cmap=cmap,origin='lower',interpolation='nearest',zorder=2)


    smallest = min(box['lat2']-box['lat1'],box['lon2']-box['lon1'])
    
    if smallest < 1.0:
        gridIncrement = 0.1
    if smallest < 2.5:
	gridIncrement = 0.5
    elif smallest < 5:
	gridIncrement = 1.0
    elif smallest < 10:
	gridIncrement = 2.5
    else:
	gridIncrement = 5.0

    parallels = np.arange(-90.,90.,gridIncrement)
    mapped.drawparallels(parallels,labels=[1,0,0,0],fontsize=10, alpha = .75)
    meridians = np.arange(-180.,180.,gridIncrement)
    mapped.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10, alpha = .75)

    if important != 'null':
	xI,yI = mapped(important[0],important[1])
	xM,yM = mapped(np.mean(lons),np.mean(lats))
	mapped.plot(xI,yI,'o',markersize=15, zorder=6, markerfacecolor = "white", markeredgecolor=mark, alpha = 1.0)
	mapped.plot(xM,yM,'x',markersize=15, zorder=6, markerfacecolor = "white", markeredgecolor=mark, alpha = 1.0)

    x, y = mapped(lons, lats) # compute map proj coordinates.
    mapped.plot(x, y, 'o', markersize=4,zorder=6, markerfacecolor=mark,markeredgecolor="none", alpha=0.30)
    if highlight != False:
        mapped.plot(x, y, 'o', markersize=4,zorder=6, markerfacecolor=highlight,markeredgecolor="none", alpha=0.03)

    
    title = '%s search for "%s",\n%s Related Tweets Found from\n%s to %s' % (dataset['name'],
                                                                            subject,
                                                                            len(dataset['data']),
                                                                            times[0],
                                                                            times[-1])
    plt.title(title)
    if subtitle != '':
   	 plt.xlabel(subtitle)

    if heatmap:
        divider = make_axes_locatable(plt.gca())
        cax = divider.append_axes("right", "5%", pad="3%")
        cbar = plt.colorbar(orientation='vertical',cax=cax)
        if level != 'full':
            plt.clim([0,level])
        cbar.set_label('Number of Tweets')
    
    if call != 'animate' and show:
        plt.show()
    return plt
Beispiel #43
0
def mapAll(lat, lon, criteria, projection = 'robin', lat_0 = "", lon_0 = "",\
           llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, \
           countries = False, counties = False, rivers = False, states = False,\
           figsize = [10,4], ax = None,\
           background = 'none', scale = 0.5, palette="", markersize = 50):
    """ Map the location of all lat/lon according to some criteria 
    
    Map the location of all lat/lon according to some criteria. The choice of 
    plotting color/marker is passed through palette according to unique 
    criteria (e.g., record name, archive type, proxy observation type).
    
    Args:
        lat (list): a list of latitude.
        lon (list): a list of longitude.
        criteria (list): a list of criteria for plotting purposes. For instance,
            a map by the types of archive present in the dataset or proxy
            observations.
        projection (string): the map projection. Refers to the Basemap
            documentation for a list of available projections. Only projections
            supporting setting the map center with a single lat/lon or with
            the coordinates of the rectangle are currently supported. 
            Default is to use a Robinson projection.
        lat_0, lon_0 (float): the center coordinates for the map. Default is
            mean latitude/longitude in the list. 
            If the chosen projection doesn't support it, Basemap will
            ignore the given values.
        llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon (float): The coordinates
            of the two opposite corners of the rectangle.
        countries (bool): Draws the countries border. Defaults is off (False). 
        counties (bool): Draws the USA counties. Default is off (False).
        rivers (bool): Draws the rivers. Default is off (False).
        states (bool): Draws the American and Australian states borders. 
            Default is off (False).
        background (string): Plots one of the following images on the map: 
            bluemarble, etopo, shadedrelief, or none (filled continents). 
            Default is none.
        scale (float): Useful to downgrade the original image resolution to
            speed up the process. Default is 0.5.
        palette (dict): A dictionary of plotting color/marker by criteria. The
            keys should correspond to ***unique*** criteria with a list of 
            associated values. The list should be in the format 
            ['color', 'marker'].
        markersize (int): The size of the marker.
        figsize (list): the size for the figure
        ax: Return as axis instead of figure (useful to integrate plot into a subplot) 
        
    Returns:
        The figure       
    """
    #Check that the lists have the same length and convert to numpy arrays
    if len(lat) != len(lon) or len(lat) != len(criteria) or len(lon) != len(
            criteria):
        sys.exit("Latitude, Longitude, and criteria list must be the same" +\
                 "length")

    # Grab the center latitude/longitude
    if not lat_0:
        lat_0 = np.mean(np.array(lat))

    if not lon_0:
        lon_0 = np.mean(np.array(lon))

    # If palette is not given, then make a random one.
    if not palette:
        marker_list = ['o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'D']
        color_list = ['#FFD600','#FF8B00','k','#86CDFA','#00BEFF','#4169E0',\
                 '#8A4513','r','#FF1492','#32CC32','#FFD600','#2F4F4F']
        # select at random for unique entries in criteria
        marker = [
            random.choice(marker_list) for _ in range(len(set(criteria)))
        ]
        color = [random.choice(color_list) for _ in range(len(set(criteria)))]
        crit_unique = [crit for crit in set(criteria)]
        #initialize the palette
        palette = {crit_unique[0]: [color[0], marker[0]]}
        for i in range(len(crit_unique)):
            d1 = {crit_unique[i]: [color[i], marker[i]]}
            palette.update(d1)

    #Make the figure
    if not ax:
        fig, ax = plt.subplots(figsize=figsize)

    map = Basemap(projection = projection, lat_0 = lat_0, lon_0 = lon_0,\
                  llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,\
                  llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon)
    map.drawcoastlines()

    # Background
    if background == "shadedrelief":
        map.shadedrelief(scale=scale)
    elif background == "bluemarble":
        map.bluemarble(scale=scale)
    elif background == "etopo":
        map.etopo(scale=scale)
    elif background == "none":
        map.fillcontinents(color='0.9', lake_color='w')
    else:
        sys.exit("Enter either 'shadedrelief','bluemarble','etopo',or'None'")

    #Other extra information
    if countries == True:
        map.drawcountries()
    if counties == True:
        map.drawcounties()
    if rivers == True:
        map.drawrivers()
    if states == True:
        map.drawrivers()

    # Get the indexes by criteria
    for crit in set(criteria):
        # Grab the indices with same criteria
        index = [i for i, x in enumerate(criteria) if x == crit]
        X, Y = map(np.array(lon)[index], np.array(lat)[index])
        map.scatter(X,
                    Y,
                    s=markersize,
                    facecolor=palette[crit][0],
                    marker=palette[crit][1],
                    zorder=10,
                    label=crit)
    plt.legend(loc='center',
               bbox_to_anchor=(1.25, 0.5),
               scatterpoints=1,
               frameon=False,
               fontsize=8,
               markerscale=0.7)

    return ax