Example #1
0
def plot(text, size):
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt
    # setup Lambert Conformal basemap.
    m = Basemap(width=3000000,height=3000000,projection='lcc',
                resolution='c',lat_0=18,lon_0=78)
    m.drawcoastlines()
    #m.fillcontinents(color='coral',lake_color='aqua')
    m.shadedrelief()
    colors = numpy.random.rand(30,3)
    lat = [17.38,13.08,12.98,19.07,22.57,26.84,26.91,28.63]
    lon = [78.49,80.28,77.61,72.88,88.34,80.95,75.78,77.25]
    df_x = [0.5,0,0.5]
    df_y = [-0.5,0,-0.5]
    f_lat = []
    f_lon = []
    f_size = []
    f_color = []
    for place_id in range(len(lat)):
        for i in range(3):
            f_lat.append(lat[place_id] + df_y[i])
            f_lon.append(lon[place_id] + df_x[i])
            f_size.append(size[place_id][i]*500)
            f_color.append(colors[text[place_id][i]])
            #m.plot(lon[place_id]+df_y[i],lat[place_id]+ df_x[i], 'bo',markersize = size[place_id][i], latlon = True)
    m.scatter(f_lon, f_lat, s = f_size, c = f_color, alpha = 0.5, latlon = True)
    m.scatter(lon, lat, s = 8000, c = 'b', alpha = 0.2, latlon = True)
    #m.scatter(f_lon, f_lat, s = f_size, c = f_color, latlon = True)
    #m.plot(f_lon,f_lat,'bo',markersize = 5, latlon = True)
    plt.show()
def make_map(
    projection='mill',
    resolution='h',
    background=None,
    llcrnrlon=-85.,
    llcrnrlat=10.,
    urcrnrlon=-45.,
    urcrnrlat=45.,
):
    m = Basemap(
        projection=projection,
        lon_0=-78.,
        resolution=resolution,
        llcrnrlon=llcrnrlon,
        llcrnrlat=llcrnrlat,
        urcrnrlon=urcrnrlon,
        urcrnrlat=urcrnrlat,
    )
    figure(num=None, figsize=(8, 6), dpi=300, facecolor='w', edgecolor='w')
    if background == 'BlueMarble':
        # m.bluemarble()
        m.shadedrelief()
    else:
        m.fillcontinents(color='#cc9966', lake_color='#99ffff')
        m.drawmapboundary(fill_color='#99ffff')
    # m.drawparallels(np.arange(10, 70, 10), alpha=0.4, color='grey', labels=[1, 1, 0, 0])
    # m.drawmeridians(np.arange(-100, 0, 10), alpha=0.4, color='grey', labels=[0, 0, 0, 1])
    m.drawcoastlines()
    m.drawcountries()
    m.drawstates()
    return m
Example #3
0
def ViewInMap(price,
              lat,
              lon,
              center_lat,
              center_lon,
              area=None,
              take_log=True):
    # 1. Draw the map background
    if area is None:
        # If undefined area, use
        area = 20
    fig = plt.figure(figsize=(8, 8))
    m = Basemap(projection='lcc',
                resolution='h',
                lat_0=center_lat,
                lon_0=center_lon,
                width=5E6,
                height=5.2E6)
    m.shadedrelief()
    m.drawcoastlines(color='gray')
    m.drawcountries(color='gray')
    m.drawstates(color='gray')

    # 2. scatter city data, with color reflecting prices
    # and size reflecting area
    if take_log:
        price = np.log10(price)
    m.scatter(lon, lat, latlon=True, c=price, s=area, cmap='Reds', alpha=0.5)
    # 3. create colorbar and legend
    plt.colorbar(label=r'$\log_{10}({\rm population})$')
    plt.clim(3, 7)
Example #4
0
def plot_evolution():
    m = Basemap(projection='mill',
            llcrnrlon=73. ,llcrnrlat=20,
            urcrnrlon=135. ,urcrnrlat=55.)
    m.shadedrelief()
    plt.title('Evolution of a Feed')

    evolution = np.load('/Users/richard/classes/294-1/project/src/locations.npy')

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

    #zipped = zip(x,y)
    #shuffle(zipped)
    #unzipped = [list(t) for t in zip(*zipped)]
    #x, y = unzipped[0], unzipped[1]

    colors = []
    i = 0
    for row in locations:
        if row[0] == 0:
            colors.append('b')
        else:
            i += 1
            colors.append('r')

    m.scatter(x,y,color=colors,s=20,marker="o")

    plt.show()
Example #5
0
def plot_gagesmap(lat, lon):
    """Create a simple point map of USGS gages in the Western US, given lat/lon
    """
    fig = plt.figure(figsize=(3.74016, 4.52756))
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    m = Basemap(width=2000000,
                height=2300000,
                resolution='l',
                projection='stere',
                lat_ts=40.0,
                lat_0=40.0,
                lon_0=-114.0)
    m.drawcoastlines(color="#333333")
    m.drawstates(linewidth=0.7, color="#333333")
    m.drawcountries(color="#333333")
    m.shadedrelief()
    parallels = np.arange(0., 81, 10)
    m.drawparallels(parallels,
                    labels=[True, False, True, False],
                    color="#333333")
    meridians = np.arange(10., 351., 10)
    m.drawmeridians(meridians,
                    labels=[False, True, False, True],
                    color="#333333")
    m.scatter(lon,
              lat,
              s=30,
              lw=1,
              marker='o',
              latlon=True,
              facecolors="none",
              edgecolors='r')
    plt.title("n = " + str(len(lon)))
    return fig
def visualization_one(pdf):
  rcParams['figure.figsize'] = (14,10)

  llon=-140
  ulon=-50
  llat=40
  ulat=65

  pdf = pdf[(pdf['Long'] > llon) & (pdf['Long'] < ulon) & (pdf['Lat'] > llat) &(pdf['Lat'] < ulat)]

  my_map = Basemap(projection='merc',
              resolution = 'l', area_thresh = 1000.0,
              llcrnrlon=llon, llcrnrlat=llat, #min longitude (llcrnrlon) and latitude (llcrnrlat)
              urcrnrlon=ulon, urcrnrlat=ulat) #max longitude (urcrnrlon) and latitude (urcrnrlat)

  my_map.drawcoastlines()
  my_map.drawcountries()
  # my_map.drawmapboundary()
  my_map.fillcontinents(color = 'white', alpha = 0.3)
  my_map.shadedrelief()

  # To collect data based on stations        

  xs,ys = my_map(np.asarray(pdf.Long), np.asarray(pdf.Lat))
  pdf['xm']= xs.tolist()
  pdf['ym'] =ys.tolist()

  #Visualization1
  for index,row in pdf.iterrows():
  #   x,y = my_map(row.Long, row.Lat)
    my_map.plot(row.xm, row.ym,markerfacecolor =([1,0,0]),  marker='o', markersize= 5, alpha = 0.75)
  #plt.text(x,y,stn)
  
  return st.pyplot()
Example #7
0
def naMap(data):
    """North America sightings map."""
    fig = plt.figure()
    m = Basemap(projection='lcc',
                llcrnrlon=-119,
                llcrnrlat=22,
                urcrnrlon=-64,
                urcrnrlat=49,
                lat_1=33,
                lat_2=45,
                lon_0=-95,
                area_thresh=10000)

    m.drawmapboundary(linewidth=1.5)
    m.drawstates()
    m.drawcountries()
    m.shadedrelief()

    # Calculate the point density
    lonx = data['lon'][np.isnan(data['lon']) == False].values
    laty = data['lat'][np.isnan(data['lat']) == False].values
    xy = np.vstack([lonx, laty])
    z = gaussian_kde(xy)(xy)

    # Sort the points by density, so that the densest points are plotted last
    idx = z.argsort()
    x, y, z = lonx[idx], laty[idx], z[idx]
    xmap, ymap = m(x, y)
    sc = m.scatter(xmap, ymap, c=z, s=30, edgecolor='', cmap=plt.cm.plasma)
    plt.title('United States UFO Sightings')
    m.colorbar(sc, location='right', pad='5%')
    plt.tight_layout()
    plt.savefig('America_UFO_Heatmap_300dpi.png', format='png', dpi=300)
    plt.show()
def create_map(llcrnrlat,
               urcrnrlat,
               llcrnrlon,
               urcrnrlon,
               relief_bool,
               width,
               map_dpi=300):
    '''creates the map'''
    print("Building the map. This might take a minute...")

    plt.figure(figsize=(width / map_dpi, (width * 0.69) / map_dpi),
               dpi=map_dpi)
    m = Basemap(projection='mill', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, \
            llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution='l')

    if relief_bool:
        m.shadedrelief()

    country_col = choose_border_color(relief_bool)
    m.drawcountries(color=country_col)

    m.fillcontinents(color=(0.9, 0.9, 0.9), lake_color='#FFFFFF', zorder=0)
    m.drawmapboundary(fill_color='#FFFFFF')

    return m
Example #9
0
    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()
Example #10
0
def worldMap(data):
    """Total world sightings map."""
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_axes([0.05, 0.05, 0.9, 0.9])

    m = Basemap(projection='kav7', lon_0=0, resolution=None)
    m.drawmapboundary(fill_color='0.3')
    m.shadedrelief()

    # Draw parallels and meridians.
    m.drawparallels(np.arange(-90., 99., 30.))
    m.drawmeridians(np.arange(-180., 180., 60.))

    # Calculate the point density
    lonx = data['lon'][np.isnan(data['lon']) == False].values
    laty = data['lat'][np.isnan(data['lat']) == False].values
    xy = np.vstack([lonx, laty])
    z = gaussian_kde(xy)(xy)

    # Sort the points by density, so that the densest points are plotted last
    idx = z.argsort()
    x, y, z = lonx[idx], laty[idx], z[idx]

    xmap, ymap = m(x, y)
    sc = m.scatter(xmap, ymap, c=z, s=20, edgecolor='', cmap=plt.cm.plasma)
    ax.set_title('World UFO Sightings')
    m.colorbar(sc, location='bottom', pad='3%')
    plt.savefig('World_UFO_Heatmap_300dpi.png', format='png', dpi=300)
    plt.show()
Example #11
0
def make_grid_map(x,
                  y,
                  themap='',
                  service='shadedrelief',
                  xpixels=500,
                  EPSG=2229,
                  **scatter_args):
    """Overlays a grid of points (passed as x,y for longitude, latitude) on a map, which is by default shaded relief
    (from www.shadedrelief.com). Can also use arcGIS ESRI map services (e.g. StreetMap_World).
    The EPSG code defines the map projection (default value here covers Southern California).
    """
    fig, ax = plt.subplots(figsize=(6, 6))
    if themap == '':
        themap = Basemap(llcrnrlon=min(x),
                         llcrnrlat=min(y),
                         urcrnrlon=max(x),
                         urcrnrlat=max(y),
                         epsg=EPSG,
                         ax=ax)
    elif not isinstance(themap, Basemap):
        raise Exception('Input projection map themap is not Basemap instance.')

    if service == 'shadedrelief': themap.shadedrelief()
    else:
        try:
            themap.arcgisimage(service=service, xpixels=xpixels, ax=ax)
        except:
            themap.arcgisimage(service='World_Street_Map',
                               xpixels=xpixels,
                               ax=ax)
    xm, ym = themap(x, y)
    ax.scatter(xm, ym, **scatter_args)
    if themap == '': return fig, themap
    else: return fig
def plot_map(lons, lats, FRPs, llcrnrlon=129,llcrnrlat=-18.5,urcrnrlon=132,urcrnrlat=-17,
                resolution='i',projection='tmerc', s = 150, marker ='^',lon_0=129.5,lat_0=-17.6, min_marker_size=2):
    
    #bins = np.linspace(0, FRP.max(), 10)
    #colour = np.digitize(FRP, bins) + min_marker_size
    #print colour
    #print colour

    m = Basemap(projection=projection, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution=resolution,lon_0=lon_0,lat_0=lat_0)
    m.drawcoastlines()
    m.drawmapboundary()
    m.drawparallels(np.arange(-40,61.,0.5), labels = [1,0,0,0])
    m.drawmeridians(np.arange(100.,140.,0.5), labels = [0,0,1,0])
    m.fillcontinents(lake_color='aqua', zorder = 0)
    m.shadedrelief()

    

    for lon, lat, FRP in zip(lons, lats, FRPs):
        
        x, y = m(lons, lats)
        #print lons.shape, FRP.shape
        m.scatter(x, y, c=FRPs, s = 300, marker ='^', zorder=10, alpha = 0.4, norm=mpl.colors.SymLogNorm(linthresh=10, vmin=0, vmax=(500)), cmap=plt.get_cmap('hot_r') )#norm=mpl.colors.SymLogNorm(linthresh=10, vmin=0, vmax=50)) #c=np.abs(FRP),
        cb = m.colorbar()
        cb.set_ticks([0,10,100,500,1000])
        
        
    return point
def show_flight(flight_info):
    m = Basemap(llcrnrlon=-180, llcrnrlat=-90, urcrnrlon=180, urcrnrlat=90, \
                projection='mill', resolution='c')
    m.shadedrelief()

    plt.show()

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

    xs = []
    ys = []

    # Plot arrival points
    NYClat, NYClon = float(flight_info[1][0]), float(flight_info[1][1])
    xpt, ypt = m(NYClon, NYClat)
    xs.append(xpt)
    ys.append(ypt)
    m.plot(xpt, ypt, 'go', markersize=20)

    # Plot departure points
    LAlat, LAlon = float(flight_info[0][0]), float(flight_info[0][1])
    xpt, ypt = m(LAlon, LAlat)
    xs.append(xpt)
    ys.append(ypt)
    m.drawgreatcircle(NYClon, NYClat, LAlon, LAlat, linewidth=2, color='b')
    m.drawcoastlines()
    m.plot(xpt, ypt, 'r^', markersize=20)

    m.plot(xs, ys, color='y', linewidth=3, label='Flight 112')

    # Customization of plotted map and displaying it
    plt.title('Flight Map')
def mapfig(ax=plt.gca()):
    m = Basemap(projection='merc',llcrnrlat=-26,urcrnrlat=-8,llcrnrlon=-18,urcrnrlon=16,resolution='l',ax=ax)
    m.drawcoastlines()
    m.drawmeridians(np.linspace(-28,16,9),labels=[0,0,0,1],linewidth=0.1)
    m.drawparallels(np.linspace(-26,-8,10),labels=[1,0,0,0],linewidth=0.1)
    m.shadedrelief(alpha=0.4)
    return m
def initmap(gps):
    # Generate Map Dimensions
    zoom = 1 # je größer, desto größer der Ausschnitt
    coords = gps.get_coordinates()
    lat0=coords.latitude/1000000.0
    lon0=coords.longitude/1000000.0
    llcrnrlon=lon0-(4.0*zoom) # links
    llcrnrlat=lat0-(2.1*zoom) # unten
    urcrnrlon=lon0+(5.0*zoom) # rechts
    urcrnrlat=lat0+(1.2*zoom) # oben
    
    print('Generating Map...')
    
    # First set up the figure, the axis, and the plot element we want to animate
    fig = plt.figure(figsize=(16,9))
    ax=fig.add_axes([0.01,0.01,0.98,0.98])
    
    
    # Thanks to this great tutorial:
    # http://peak5390.wordpress.com/2012/12/08/mapping-global-earthquake-activity-a-matplotlib-basemap-tutorial/
    m = Basemap(llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat,urcrnrlon=urcrnrlon,urcrnrlat=urcrnrlat,
               resolution='l',projection='tmerc',lon_0=lon0,lat_0=lat0)

    m.drawcoastlines()
    #m.fillcontinents(color='gray')
    # draw parallels and meridians.
    m.drawparallels(np.arange(-40,61.,2.))
    m.drawmeridians(np.arange(-30.,43.,2.))
    m.drawmapboundary()
    m.drawcountries()
    m.shadedrelief()

    return fig, plt, m
def plot_tsp_path(gps, flags, tsp_tour):
    plt.figure(figsize=(24, 12))
    m = Basemap(projection='ortho', lon_0=20.0, lat_0=20.0, resolution=None)
    m.shadedrelief()

    for (lon, lat), flag in zip(gps, flags):
        x, y = m(lon, lat)
        im = OffsetImage(flag[..., ::-1], zoom=0.8)
        ab = AnnotationBbox(im, (x, y), xycoords='data', frameon=False)
        m._check_ax().add_artist(ab)

    num_countries = len(tsp_tour)
    last_country = 0
    current_country = 0
    path_indices = [0]
    for _ in range(num_countries):
        for j in range(num_countries):
            if tsp_tour[current_country][j] and j != last_country:
                last_country = current_country
                current_country = j
                path_indices.append(current_country)
                break

    lat = [gps[i][1] for i in path_indices]
    lon = [gps[i][0] for i in path_indices]

    x, y = m(lon, lat)
    m.plot(x, y, 'o-', markersize=5, linewidth=3)

    plt.title("Country locations with TSP solution")
    plt.show()
Example #17
0
def make_basemap_image(df):
    print(df.head())
    scaler = MinMaxScaler(feature_range=(10, 100))
    size = scaler.fit_transform(df['Yearly'].values.reshape(-1, 1))

    fig = plt.figure(figsize=(8, 8))
    m = Basemap(projection='lcc',
                resolution='h',
                lat_0=df['Lat'].mean(),
                lon_0=df['Long'].mean(),
                width=1E6 * .75,
                height=1.2E6 * .75)

    m.shadedrelief()
    m.drawcoastlines(color='black')
    m.drawcountries(color='gray')
    m.drawstates(color='black')

    parallels = np.arange(0., 81, 2.)
    meridians = np.arange(-360, 351., 2.)
    # labels = [left,right,top,bottom]
    m.drawparallels(parallels, labels=[False, True, False, False])
    m.drawmeridians(meridians, labels=[False, False, False, True])

    m.scatter(df['Long'].values,
              df['Lat'].values,
              latlon=True,
              c=df['Yearly'].values,
              cmap='coolwarm',
              alpha=0.75,
              s=size,
              marker='o')

    plt.savefig('scatterMap.png')
    def visualze_community_location(self,
                                    markerSize=10,
                                    figure_file_name="test.png"):
        # 1. Draw the map background
        fig = plt.figure(figsize=(8, 8))
        m = Basemap(projection='lcc',
                    resolution='h',
                    lat_0=self.map_limit['lat_0'],
                    lon_0=self.map_limit['lon_0'],
                    width=self.map_limit['width'],
                    height=self.map_limit['height'])
        m.shadedrelief()
        m.drawcoastlines(color='gray')
        m.drawcountries(color='gray')
        m.drawstates(color='gray')
        cmap = plt.cm.seismic
        norm = matplotlib.colors.Normalize(vmin=0, vmax=len(self.partition))
        l = 0
        key_list = list(self.edge_dict.keys())
        maker_list = [
            '.', ',', 'o', 'v', '^', '<', '>', '1', '2', '3', '4', '8', 's',
            'p', 'P', '*', 'h', 'H', '+', 'x', 'X', 'D', 'd', '|', '_'
        ]

        node_community = [[
            j for j, lst in enumerate(self.partition) if node in lst
        ][0] for node in self.nodes]
        node_community_size = np.array(
            [len(self.partition[community]) for community in node_community])
        node_index = np.lexsort((node_community, -node_community_size))
        node_community_size_unique = np.sort([len(k)
                                              for k in self.partition])[::-1]

        for i in range(len(self.nodes)):
            lat1 = self.data_dict['StationLoc'][np.where(
                self.data_dict['siteID'] == self.nodes[i])[0][0]][1]
            lon1 = self.data_dict['StationLoc'][np.where(
                self.data_dict['siteID'] == self.nodes[i])[0][0]][0]
            node1_community = [
                j for j, lst in enumerate(self.partition)
                if self.nodes[i] in lst
            ][0]
            x, y = m(lon1, lat1)
            #m.scatter(x, y, s = markerSize, marker = maker_list[node1_community % len(maker_list)], color = cmap(norm(node1_community)), label = str(node1_community))
            community_sorted_by_size = next(
                m for m, val in enumerate(node_community_size_unique)
                if sum(node_community_size_unique[:(m + 1)]) > np.where(
                    node_index == i)[0][0])
            plt.annotate(str(community_sorted_by_size + 1), xy=(x, y))
        sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
        sm.set_array([])
        handles, labels = fig.gca().get_legend_handles_labels()
        index = np.argsort([np.int(x) for x in labels])
        by_label = OrderedDict(
            zip(np.array(labels)[index],
                np.array(handles)[index]))
        #fig.legend(by_label.values(), by_label.keys(), loc = "center right", title = "Label")
        fig.savefig(figure_file_name)
        plt.close(fig)
Example #19
0
def draw_map(lons, lats, dataQ, nameQ):
    """
      Draw the contour filled map of 2D data array
      such as statistics of Onset or End date of
      the wet season over a given region.
   """
    xs, ys = numpy.meshgrid(lons, lats)
    m = Basemap(projection='cyl',
                llcrnrlon=min(lons) - 1.5,
                llcrnrlat=min(lats) - 0.5,
                urcrnrlon=max(lons) + 1,
                urcrnrlat=max(lats) + 0.5,
                resolution='i')

    # Add continent and admin outlines
    m.drawcoastlines(linewidth=1.25)
    m.drawcountries(linewidth=1.0)
    m.shadedrelief(ax=None, scale=0.5)

    # Other parameters
    if nameQ in ['meanOnset']:
        intQ = 2
        cmapName = 'jet_r'
        minQ = numpy.min(dataQ)
        maxQ = numpy.max(dataQ)
    else:
        intQ = 14
        cmapName = 'hsv'  #'jet_r'
        minQ = 1
        maxQ = 364

    boundsQ = numpy.arange(minQ, maxQ + intQ, intQ)
    normQ = mpl.colors.BoundaryNorm(boundsQ, len(boundsQ) - 1)
    cmapQ = plt.cm.get_cmap(cmapName, len(boundsQ))

    # Filled contours
    cnt = m.contourf(xs,
                     ys,
                     dataQ,
                     vmin=minQ,
                     vmax=maxQ,
                     levels=boundsQ,
                     cmap=cmapQ,
                     norm=normQ,
                     alpha=0.75)
    #antialiased = True )

    # Colorbar
    cb = m.colorbar(cnt, location='right', pad=0.15, size='3%')
    cb.set_clim(minQ, maxQ)
    cb.set_ticks(boundsQ)
    boundsQstr = numpy.array(['{:.0f}'.format(bnd) for bnd in boundsQ])
    boundsQdate = [
        datetime.strptime(bnd, '%j').date().strftime('%b-%d')
        for bnd in boundsQstr
    ]
    cb.ax.set_yticklabels(boundsQdate, fontsize=10)

    return m
Example #20
0
def location_wage(rdd, title, lon_0, lat_0, width, height, gridsize):
    location_wage_yr = rdd.map(lambda x: (x[10], (x[7], 1, x[7])))
    #[0]: key(location); [1][0]: sumover all records; [1][1]: number of records; [1][2]: max value

    location_wage_stat = location_wage_yr.reduceByKey(
        lambda x, y: (x[0] + y[0], x[1] + y[1], max(x[2], y[2])))
    location_wage_stat = location_wage_stat.map(convert_name_to_location)

    result = location_wage_stat.collect()

    from mpl_toolkits.basemap import Basemap

    # # create figure and axes instances
    fig = plt.figure(figsize=(14, 14))
    # create polar stereographic Basemap instance.
    # width and height are in meters
    m = Basemap(width=width,height=height,projection='lcc',\
                resolution='f',lon_0=lon_0,lat_0=lat_0)
    #m.drawlsmask(land_color='green',ocean_color='aqua',lakes=True)
    # draw coastlines, state and country boundaries, edge of map.
    #m.bluemarble()
    m.shadedrelief()
    #m.etopo()
    x = []
    y = []
    z = []

    for record in result:
        if record[0] != None:
            xpt, ypt = m(record[0][1], record[0][0])
            # print>>sys.stdout, record
            # print>>sys.stdout, xpt
            # print>>sys.stdout, ypt
            x.append(int(xpt))
            y.append(int(ypt))
            z.append(record[1][0] / float(record[1][1]) / 1000)

    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    binplot = m.hexbin(np.array(x),
                       np.array(y),
                       C=np.array(z),
                       reduce_C_function=np.mean,
                       gridsize=gridsize,
                       mincnt=0,
                       linewidths=0.5,
                       edgecolors='k',
                       zorder=10)
    #m.scatter(x,y,40,z,cmap=plt.cm.jet,marker='o',edgecolors='none',alpha=.5, zorder=10)
    # plot colorbar for markers.
    m.colorbar(binplot, pad='8%', label='Mean Total Income (k$)')
    plt.title(title, fontsize=20)
    binplot.set_clim(vmin=0, vmax=150)
    #plt.show()
    #print>>sys.stdout, location_wage_stat.take(10)
    plt.savefig(title)
    return location_wage_stat.keys().count()
Example #21
0
def trace_route(ip_address: str) -> None:
    if platform.system() in ('Linux', 'Darwin'):
        command = ['traceroute', '-m', '25', '-n', ip_address]
    elif platform.system() == 'Windows':
        tracert_path = Path('C:') / 'Windows' / 'System32' / 'TRACERT.exe'
        # alt: tracert_path = Path(subprocess.run(['where.exe', 'tracert'], capture_output=True, encoding='utf-8').stdout.rstrip())
        command = [str(tracert_path), '-h', '25', '-d', '-4', ip_address]
    else:
        print(
            "Sorry, this Python program does not have support for your current operating system!"
        )
        sys.exit(-1)

    # Start traceroute command
    proc = subprocess.Popen(command,
                            stdout=subprocess.PIPE,
                            shell=True,
                            universal_newlines=True)

    # Plot a pretty enough map
    fig = plt.figure(figsize=(10, 6), edgecolor='w')
    m = Basemap(projection='mill', lon_0=0, resolution='l')
    m.shadedrelief(scale=0.05)

    # Where we are coming from
    last_lon = None
    last_lat = None

    # Parse individual traceroute command lines
    for line in proc.stdout:
        print(line, end='')

        if platform.system() == 'Windows' and len(line.split()) != 8:
            continue

        hop_ip = line.split()[1 if platform.system() in ('Linux', 'Darwin')
                              else 7]  # First step already handled other cases

        if hop_ip in ('*', 'to'):
            continue

        (lat, lon) = get_location(hop_ip)

        if (lat is None):
            continue

        if last_lat is not None and (last_lat - lat + last_lon - lon) != 0.0:
            # print(lastLat, lastLon, lat, lon)
            x, y = m(lon, lat)
            m.scatter(x, y, 10, marker='o', color='r')
            line, = m.drawgreatcircle(last_lon, last_lat, lon, lat, color='b')

        last_lat = lat
        last_lon = lon

    plt.tight_layout()
    plt.show()
Example #22
0
 def plotM(self, name):
     plt.figure()
     m = Bm(llcrnrlon=self.lon1,
            llcrnrlat=self.lat1,
            urcrnrlon=self.lon2,
            urcrnrlat=self.lat2,
            projection='mill')
     m.shadedrelief()
     plt.savefig(name + '.png', dpi=500)
Example #23
0
def plot_station_locs(stations,target_latlon):
    
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    
    # "unpack" data from air quality object
    #print(aq_obj.monitor_info)
    #monitor_info = aq_obj.monitor_info
    my_lon = stations['Longitude'][0]
    my_lat = stations['Latitude'][0]
    r_max = 150
    #param_code = aq_obj.param
    #site_name = aq_obj.site_name
    
    num_stations = len(stations)
    
    # create colors to correspond to each of the stations
    RGB_tuples = [(x/num_stations, (1-x/num_stations),.5) for x in range(0,num_stations)]
    color_dict = {}
    for x in range(0,num_stations):
        color_dict[stations.index[x]] = RGB_tuples[x]
    
    # set viewing window for map plot
    scale_factor = 60.0 # lat/lon coords to show from center point per km of r_max
    left_lim = my_lon-r_max/scale_factor
    right_lim = my_lon+r_max/scale_factor
    bottom_lim = my_lat-r_max/scale_factor
    top_lim = my_lat+r_max/scale_factor
    
    
    fig = plt.figure(figsize=(20, 12), facecolor='w')    
    
    m = Basemap(projection='merc',resolution='c',lat_0=my_lat,lon_0=my_lon,llcrnrlon=left_lim,llcrnrlat=bottom_lim,urcrnrlon=right_lim,urcrnrlat=top_lim)
    m.shadedrelief()
    m.drawstates()
    m.drawcountries()
    m.drawrivers()
    m.drawcoastlines()
    
    plt.show()
    
    # plot each EPA site on the map, and connect it to the soiling station with a line whose width is proportional to the weight
    for i in range(0,num_stations):
        
        (x,y) = m(stations.iloc[i]['Longitude'],stations.iloc[i]['Latitude'])
        m.plot(x,y,'o',color = RGB_tuples[i])
        
        (x,y) = m(stations.iloc[i]['Longitude'],stations.iloc[i]['Latitude'])
        plt.text(x,y,stations.index[i])
        
    (x,y) = m(target_latlon[1],target_latlon[0])
    m.plot(x,y,'x',color = 'r',ms=8)
    
    return fig    
def rendermap(projection):
    '''
    For sinu, moll, hammer, npstere, spstere, nplaea, splaea, npaeqd,
    spaeqd, robin, eck4, kav7, or mbtfpq, the values of
    llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, width and height
    are ignored (because either they are computed internally,
    or entire globe is always plotted).
    '''
    m=Basemap(llcrnrlon=-12.0, \
            llcrnrlat=32.0, \
            urcrnrlon=54.4, \
            urcrnrlat=65.3, \
            llcrnrx=None, \
            llcrnry=None, \
            urcrnrx=None, \
            urcrnry=None, \
            width=None, \
            height=None, \
            projection=projection, \
            resolution='h', \
            area_thresh=1000, \
            rsphere=6370997.0, \
            ellps=None, \
            lat_ts=None, \
            lat_1=None, \
            lat_2=None, \
            lat_0=51.0, \
            lon_0=13.0, \
            lon_1=None, \
            lon_2=None, \
            o_lon_p=None, \
            o_lat_p=None, \
            k_0=None, \
            no_rot=True, \
            suppress_ticks=True, \
            satellite_height=35786000, \
            boundinglat=None, \
            fix_aspect=True, \
            anchor='C', \
            celestial=False, \
            round=False, \
            epsg=None, \
            ax=None)
    
    m.drawcountries(linewidth=0.2, linestyle='solid', color='w', antialiased=1, ax=None, zorder=None)
    
    m.drawparallels(np.arange(-90.,120.,10.),labels=[0,0,0,0],linewidth=0.2) # draw parallels
    m.drawmeridians(np.arange(0.,420.,10.),labels=[0,0,0,0],linewidth=0.2) # draw meridians

    m.shadedrelief()

    plt.title('\'' + projection + '\' Projection', fontsize=12)
    plt.savefig(fname, dpi=300, bbox_inches='tight', transparent=True)
    plt.close()
    print('Saved \'' + fname + '\'')
Example #25
0
def show_coord_topo(windpark, title, show = True):
    """Plot the topology of a given windpark

    Topographic Map with farms
    see: http://matplotlib.org/basemap/users/examples.html
    Basemap

    Parameters
    ----------

    windpark : Windpark
               A given windpark to show the topology.
    """

    turbines = windpark.get_turbines()
    target = windpark.get_target()
    radius = windpark.get_radius()

    #pack latitude and longitude in lists
    rel_input_lat = []
    rel_input_lon = []
    for row in turbines:
        rel_input_lat.append(np.float64(row.latitude))
        rel_input_lon.append(np.float64(row.longitude))

    targetcoord = [0.0, 0.0]
    targetcoord[0] = np.float64(target.latitude)
    targetcoord[1] = np.float64(target.longitude)

    graddiff = (radius/111.0) + 0.3 # degree in km

    m = Basemap(fix_aspect=False, projection='stere', lon_0=targetcoord[1], lat_0=targetcoord[0],\
        llcrnrlon = targetcoord[1]-graddiff, llcrnrlat = targetcoord[0]-graddiff ,\
        urcrnrlon = targetcoord[1]+graddiff, urcrnrlat = targetcoord[0]+graddiff ,\
        rsphere=6371200., resolution = 'l', area_thresh=1000)
    # Target
    x_target,y_target = m(targetcoord[1],targetcoord[0])
    # Input Farms
    rel_inputs_lon, rel_inputs_lat = m(rel_input_lon, rel_input_lat)

    # labels = [left,right,top,bottom]
    parallels = np.arange(int(targetcoord[0]-3), int(targetcoord[0]+3), 1.)
    #m.drawparallels(parallels,labels=[False,True,True,False])
    meridians = np.arange(int(targetcoord[1]-3), int(targetcoord[1]+3), 1.)
    #m.drawmeridians(meridians,labels=[True,False,False,True])

    # plot farms in the radius
    m.scatter(rel_inputs_lon, rel_inputs_lat,20, marker='o', color="#000000")
    m.scatter(x_target, y_target, 20, marker='o', color="r")
    m.shadedrelief()
    plt.title(title)

    if(show):
        plt.show()
Example #26
0
def show_coord_topo(windpark, title, show=True):
    """Plot the topology of a given windpark

    Topographic Map with farms
    see: http://matplotlib.org/basemap/users/examples.html
    Basemap

    Parameters
    ----------

    windpark : Windpark
               A given windpark to show the topology.
    """

    turbines = windpark.get_turbines()
    target = windpark.get_target()
    radius = windpark.get_radius()

    #pack latitude and longitude in lists
    rel_input_lat = []
    rel_input_lon = []
    for row in turbines:
        rel_input_lat.append(np.float64(row.latitude))
        rel_input_lon.append(np.float64(row.longitude))

    targetcoord = [0.0, 0.0]
    targetcoord[0] = np.float64(target.latitude)
    targetcoord[1] = np.float64(target.longitude)

    graddiff = (radius / 111.0) + 0.3  # degree in km

    m = Basemap(fix_aspect=False, projection='stere', lon_0=targetcoord[1], lat_0=targetcoord[0],\
        llcrnrlon = targetcoord[1]-graddiff, llcrnrlat = targetcoord[0]-graddiff ,\
        urcrnrlon = targetcoord[1]+graddiff, urcrnrlat = targetcoord[0]+graddiff ,\
        rsphere=6371200., resolution = 'l', area_thresh=1000)
    # Target
    x_target, y_target = m(targetcoord[1], targetcoord[0])
    # Input Farms
    rel_inputs_lon, rel_inputs_lat = m(rel_input_lon, rel_input_lat)

    # labels = [left,right,top,bottom]
    parallels = np.arange(int(targetcoord[0] - 3), int(targetcoord[0] + 3), 1.)
    #m.drawparallels(parallels,labels=[False,True,True,False])
    meridians = np.arange(int(targetcoord[1] - 3), int(targetcoord[1] + 3), 1.)
    #m.drawmeridians(meridians,labels=[True,False,False,True])

    # plot farms in the radius
    m.scatter(rel_inputs_lon, rel_inputs_lat, 20, marker='o', color="#000000")
    m.scatter(x_target, y_target, 20, marker='o', color="r")
    m.shadedrelief()
    plt.title(title)

    if (show):
        plt.show()
Example #27
0
def main():
	trip_data = data_utils.load_trip_data()
	station_data = data_utils.load_station_data()
	zip_data = data_utils.load_zip_data()
	
	trip_coordinates_zip = data_utils.get_trip_coordinates_zip(trip_data, station_data)
	trip_coordinates_home_coordinates = data_utils.get_trip_coordinates_home_coordinates(trip_coordinates_zip, zip_data)

	home_coordinates = zip(*trip_coordinates_home_coordinates)[2]

	#home_coordinates = filter(data_utils.is_bay_area_resident, home_coordinates)
	
	lat, lon = zip(*home_coordinates)

#	m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,\
#			llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')	#World
#	m = Basemap(projection='merc',llcrnrlat=25,urcrnrlat=50,\
#			llcrnrlon=-130,urcrnrlon=-70,lat_ts=20,resolution='c')	#USA

#	m = Basemap(projection='merc',llcrnrlat=35.5,urcrnrlat=39.9,\
#			llcrnrlon=-124.5,urcrnrlon=-118.5,lat_ts=20,resolution='c')	#Norcal

	m = Basemap(projection='merc',llcrnrlat=37.304294,urcrnrlat=37.840926,\
			llcrnrlon=-122.559453,urcrnrlon=-121.859292,lat_ts=20,resolution='c')	#Bay Area

	m.shadedrelief()
	#m.drawlsmask()

	#m.drawcoastlines()
	m.drawcountries()
	m.drawstates()


	#m.fillcontinents(color='0.8')
	# draw parallels and meridians.
	#m.drawparallels(np.arange(-90.,91.,30.))
	#m.drawmeridians(np.arange(-180.,181.,60.))
	#m.drawmapboundary(fill_color='aqua')
	xs,ys = m(lon,lat)

	m.plot(xs, ys, latlon=False, linestyle='circle marker', marker='o', markerfacecolor='blue', markersize=5)

	#start_coordinates = zip(*trip_coordinates_home_coordinates)[0]
	#lat, lon = zip(*start_coordinates)
	#xs,ys = m(lon,lat)
	#m.plot(xs, ys, latlon=False, linestyle='circle marker', marker='o', markerfacecolor='green', markersize=5)

	#end_coordinates = zip(*trip_coordinates_home_coordinates)[1]
	#lat, lon = zip(*end_coordinates)
	#xs,ys = m(lon,lat)
	#m.plot(xs, ys, latlon=False, linestyle='circle marker', marker='o', markerfacecolor='red', markersize=5)

	plt.show()
Example #28
0
def mapplotOIB(x, y, z, title, units):
    import matplotlib.pyplot as plt
    #########################################
    ### FULL FAG070
    import matplotlib.cm as cm
    from mpl_toolkits.basemap import Basemap
    fig = plt.figure(figsize=(8, 8))
    #create basemap
    m = Basemap(width=700000,
                height=1100000,
                resolution='h',
                projection='stere',
                area_thresh=100000.0,
                lat_ts=-55,
                lat_0=-68,
                lon_0=-65.)
    # Draw the coastlines on the map
    m.drawcoastlines()
    # Draw country borders on the map
    m.drawcountries()
    # Fill the land with grey
    #m.fillcontinents(color = 'gainsboro')
    #m.drawmapboundary(fill_color='steelblue')
    #m.bluemarble()
    #m.etopo()
    m.shadedrelief()
    m.drawcoastlines()
    m.drawparallels(np.arange(-80., 81., 5.), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180., 181., 5.), labels=[0, 0, 0, 1])
    # Define our longitude and latitude points
    # We have to use .values because of a wierd bug when passing pandas data
    # to basemap.
    x1, y1 = m(x.values, y.values)
    # Plot them using round markers of size 6
    #m.plot(x, y, 'ro', markersize=2)
    m.scatter(x1,
              y1,
              c=z,
              marker="o",
              cmap=cm.jet,
              s=40,
              edgecolors='none',
              vmin=-100,
              vmax=200)  #,vmin=-150,vmax=50
    c = plt.colorbar(orientation='vertical', shrink=0.5)
    c.set_label(units)
    #plt.show()
    #plt.tight_layout()
    plt.suptitle(title, y=1.02)
    plt.savefig(infile + '_' + title + '_mapplot.png',
                bbox_inches='tight')  # save the figure to file
    #plt.close(m)
    return
Example #29
0
def geramapa(idx):
    lon = stars[idx].ra - datas[idx].sidereal_time('mean', 'greenwich')

    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution='l')
# draw coastlines, country boundaries, fill continents.
    m.shadedrelief()
    m.drawcoastlines(linewidth=0.25)
    m.drawcountries(linewidth=0.4)
    m.drawstates(linewidth=0.4)
#m.fillcontinents(color='coral',lake_color='aqua')
# draw the edge of the map projection region (the projection limb)
#m.drawmapboundary(fill_color='aqua')
# draw lat/lon grid lines every 30 degrees.
    m.drawmeridians(np.arange(0,360,30))
    m.drawparallels(np.arange(-90,90,30))
    if os.path.isfile(sitearq) == True:
        xpt,ypt = m(sites['lon'],sites['lat'])
        m.plot(xpt,ypt,'bo')
    CS=m.nightshade(datas[idx].datetime, alpha=0.2)
    a, b =m(lon.value, stars[idx].dec.value)
    a = a*u.m
    b = b*u.m
    dista = (dist[idx].to(u.km)*ca[idx].to(u.rad)).value*u.km
    disterr = (dist[idx].to(u.km)*erro.to(u.rad)).value*u.km
    ax = a + dista*np.sin(pa[idx])
    ax2 = ax + 1000*u.km*vec*np.cos(pa[idx])
    ax3 = ax2 - tamanho/2*np.sin(pa[idx])
    ax4 = ax2 + tamanho/2*np.sin(pa[idx])
    ax5 = a + (dista-disterr)*np.sin(pa[idx]) + 1000*u.km*vec*np.cos(pa[idx])
    ax6 = a + (dista+disterr)*np.sin(pa[idx]) + 1000*u.km*vec*np.cos(pa[idx])
    by = b + dista*np.cos(pa[idx])
    by2 = by - 1000*u.km*vec*np.sin(pa[idx])
    by3 = by2 - tamanho/2*np.cos(pa[idx])
    by4 = by2 + tamanho/2*np.cos(pa[idx])
    by5 = b + (dista-disterr)*np.cos(pa[idx]) - 1000*u.km*vec*np.sin(pa[idx])
    by6 = b + (dista+disterr)*np.cos(pa[idx]) - 1000*u.km*vec*np.sin(pa[idx])
    m.plot(ax,by, 'ro', markersize=20)
    m.plot(ax2.to(u.m),by2.to(u.m), 'ro', markersize=8)
    m.plot(ax3.to(u.m), by3.to(u.m), 'b')
    m.plot(ax4.to(u.m), by4.to(u.m), 'b')
    m.plot(ax5.to(u.m), by5.to(u.m), 'r--')
    m.plot(ax6.to(u.m), by6.to(u.m), 'r--')

    fig = plt.gcf()
    fig.set_size_inches(18.0, 15.0)
    plt.title('-{} D={}- dots each 1000km or {:.2f} <> offsets (mas): {:.1f}, {:.1f}\n'.format(obj, tamanho, np.absolute(1000*u.km/vel[idx]), off_ra[idx].value, off_de[idx].value), fontsize=25, fontproperties='FreeMono')
    plt.xlabel('\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta  R*   K*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f} {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
        .format(datas[idx].iso, dados['afh'][idx], dados['afm'][idx], dados['afs'][idx], dados['ded'][idx], dados['dem'][idx], dados['des'][idx], ca[idx].value, pa[idx].value, dados['vel'][idx],
        dist[idx].value, dados['mR'][idx], dados['mK'][idx], dados['long'][idx]), fontsize=21, fontproperties='FreeMono')
    plt.savefig('{}_{}.png'.format(obj, datas[idx].isot),dpi=100)
    print 'Gerado: {}_{}.png'.format(obj, datas[idx].isot)
    plt.clf()
Example #30
0
def prepare_background(map_type):
    """
    Create an cylindrical equidistant map projection using low resolution
    coastlines.

    """
    outfile = os.path.join(*PLOT_DIR, '%s_map.png' % map_type)

    print("Generating Background Map %s ..." % outfile)
    fig = plt.figure(1)
    left = 0.0
    bottom = 0.0
    width = 1.0
    height = 1.0
    ax = fig.add_axes([left, bottom, width, height])

    print('    Creating Generic Basemap...')
    map = Basemap(projection='cyl',
                  llcrnrlon=-180,
                  llcrnrlat=-90,
                  urcrnrlon=180,
                  urcrnrlat=90,
                  resolution='l',
                  ax=ax)

    print('    Adding features - lines...')
    # draw coastlines, country boundaries, state boundaries
    map.drawcoastlines(linewidth=0.25)
    map.drawcountries(linewidth=0.25)
    map.drawstates(linewidth=0.15)

    print('    Adding features - land/ocean...')
    if map_type == 'basic':
        map.drawlsmask(land_color='white', ocean_color='aqua', resolution='l')
        map.drawlsmask(resolution='l')
    elif map_type == 'marble':
        map.bluemarble()
    elif map_type == 'etopo':
        map.etopo()
    else:  # default 'shaded'
        map.shadedrelief()
    print('    Saving...')
    ax.axis('off')
    fig.savefig(outfile,
                frameon=False,
                bbox_inches='tight',
                pad_inches=0,
                dpi=600)
    plt.clf()
    plt.close()
    gc.collect()
Example #31
0
def daily_outputs(dictionary, key, cs, nr_of_days):
    """
    Create map with daily output for precipitation and temperature
    :param dictionary: Dictionary containing information about file name, variable name, map title and scalebar text
    :param key: The key in the dictionary pointing to the file that should be used
    :param cs: The colour scheme to be used for the output maps, e.g. 'Blues' or 'Oranges'
    :param nr_of_days: Number of maps (one map for each day) that the function should return
    :return: One map for each day, showing daily precipitation or temperature values
    """

    # Read data from dictionary
    datas = read_data(dictionary, key)[0]
    scalebar = dictionary[key][2]

    # Define the date range that should be used for the output maps
    days = pd.date_range(start='1980-12-31', end='2010-12-31', freq='D', closed='right')
    days = pd.Series(days.format())

    # User defined data type
    type = raw_input('Which type of data should be used? (e.g. mean precipitation, maximum temperature)')

    for i in range(0, nr_of_days):
        # Define the base map projection, extent and appearance
        m = Basemap(projection='tmerc', resolution='l', height=2300000, width=3500000, lat_0=29, lon_0=82)
        m.drawmapboundary()
        m.drawparallels(np.arange(-80., 81., 10.), labels=[1, 0, 0, 0])
        m.drawmeridians(np.arange(-180., 181., 10.), labels=[0, 0, 0, 1])
        m.drawcountries()
        m.shadedrelief()

        # Obtain the latitudes and longitudes, point to data and read the minimum and maximum values for the scalebar
        xi, yi = m(tr_lon, tr_lat)
        netcdf = m.pcolormesh(xi, yi, datas[i], cmap=cs)
        m.colorbar(netcdf, location='bottom', pad='10%', label=scalebar)
        sb_min = read_data(dictionary, key)[1]
        sb_max = read_data(dictionary, key)[2]
        plt.clim(sb_min, sb_max)

        # Define location for map output and create filename and title for the map
        path = '/users/froedevrolijk/Geo/outputs_hiaware/entire_IGB/daily'
        filename = dictionary[key][1]+'{0}.png'.format(days[0:nr_of_days][i])
        plt.title(type + ' for {0}'.format(days[0:nr_of_days][i]))
        filename = os.path.join(path, filename)

        # If the output file already exists, remove the old file
        if os.path.isfile(filename):
            os.remove(filename)

        # Save the map, and close the plotting window
        plt.savefig(filename)
        plt.close()
def draw(G, path=None):
    plt.figure(figsize=(6, 12))
    m = Basemap(projection='merc',
                llcrnrlon=5,
                llcrnrlat=46,
                urcrnrlon=16,
                urcrnrlat=56,
                lat_ts=0,
                resolution='i',
                suppress_ticks=True)
    # map network nodes to position relative to basemap, remove nodes that don't have location
    G2 = G.copy()
    pos = {}
    for n in G.nodes():
        # remove nodes that do not have lat,long info
        if 'Longitude' not in G.node[n].keys():
            G2.remove_node(n)
            continue
        long = G.node[n]['Longitude']
        lat = G.node[n]['Latitude']
        pos[n] = m(long, lat)

    #get values for drawing nodes,edges in color
    values = [G2.node[n]['Value'] for n in G2.nodes()]
    values_edges = [G2.edges[e]['Value'] for e in G2.edges()]

    # draw network
    graph = G2
    nx.draw_networkx_nodes(G=graph,
                           pos=pos,
                           node_list=graph.nodes(),
                           node_color=values,
                           alpha=0.4,
                           node_size=10,
                           cmap=plt.get_cmap('Pastel1'))
    # nx.draw_networkx_nodes(G = graph, pos = pos, node_list = nodelist['G2'], node_color = 'y', alpha = 0.2, node_size=10)
    nx.draw_networkx_edges(G=graph,
                           pos=pos,
                           edge_color=values_edges,
                           cmap=plt.get_cmap('Pastel1'),
                           arrows=False,
                           width=2)
    # m.drawcoastlines(color='black',linewidth=0.5)
    m.drawcountries(color='black', linewidth=1)
    # m.fillcontinents(color="#FFDDCC", lake_color='#DDEEFF')
    # m.drawmapboundary(fill_color="#DDEEFF")
    m.shadedrelief()
    if path:
        plt.savefig(path, dpi=300, bbox_inches='tight')
    plt.show()
def create_map(lon, lat):
    m = Basemap(llcrnrlon=np.min(lon) - 5.,
                llcrnrlat=np.min(lat) - 5.,
                urcrnrlon=np.max(lon) + 5.,
                urcrnrlat=np.max(lat) + 5.,
                resolution='i',
                projection='merc',
                lon_0=np.mean(lon),
                lat_0=np.mean(lat))
    m.shadedrelief()
    m.drawparallels(np.arange(-40, 80., 5.), color='gray')
    m.drawmeridians(np.arange(-30., 80., 5.), color='gray')

    return m
Example #34
0
    def _display_gps_map(self, df, labels, map_title):
        '''print the longitude & latitude GPS coordinates of the dataframe within the map bounderies'''

        print("GIS_Map_Viz: _display_gps_map ...")
        fig = plt.figure(figsize=(20, 10))
        plt.title(map_title)

        m = Basemap(projection='merc',
                    llcrnrlat=self.gps_bounderies_dict['lat_min'] - 0.5,
                    urcrnrlat=self.gps_bounderies_dict['lat_max'] + 0.5,
                    llcrnrlon=self.gps_bounderies_dict['lon_min'] - 0.5,
                    urcrnrlon=self.gps_bounderies_dict['lon_max'] + 0.5,
                    resolution='i')

        # Reference: https://matplotlib.org/basemap/users/geography.html
        m.drawmapboundary(fill_color='#85A6D9')
        m.drawcoastlines(color='#6D5F47', linewidth=.8)
        m.drawrivers(color='green', linewidth=.4)
        m.shadedrelief()
        m.drawcountries()
        m.fillcontinents(lake_color='aqua')

        mycmap = matplotlib.colors.LinearSegmentedColormap.from_list(
            "", ["green", "yellow", "red"])
        longitudes = df[self.longitude_feature_name].tolist()
        latitudes = df[self.latitude_feature_name].tolist()
        if labels is None:
            labels = 'darkblue'
            wp = mpatches.Patch(color='darkblue', label='water points')
            plt.legend(handles=[wp], title='Location')
        else:
            labels = labels.cat.codes
            wp_functional = mpatches.Patch(color='green',
                                           label='water points: functional')
            wp_need_repair = mpatches.Patch(
                color='red', label='water points: non functional')
            wp_non_functional = mpatches.Patch(
                color='yellow', label='water points: functional needs repair')
            plt.legend(
                handles=[wp_functional, wp_need_repair, wp_non_functional],
                title='Location and Status')

        m.scatter(longitudes,
                  latitudes,
                  s=0.05,
                  zorder=2,
                  latlon=True,
                  c=labels,
                  cmap=mycmap)
        plt.show()
Example #35
0
    def plot(self, datos, name, title):
        plt.figure()
        m = Bm(llcrnrlon=self.lon1,
               llcrnrlat=self.lat1,
               urcrnrlon=self.lon2,
               urcrnrlat=self.lat2,
               projection='mill')
        m.shadedrelief()
        m.imshow(datos[:])
        m.colorbar()

        #plt.show()
        plt.title(title)
        plt.savefig(name + '.png', dpi=500)
Example #36
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 data_plotting(q):
    plt.ion()  # Interactive mode
    llon = -130
    ulon = 100
    llat = -30
    ulat = 60
    rcParams['figure.figsize'] = (14, 10)
    my_map = Basemap(
        projection='merc',
        resolution='l',
        area_thresh=1000.0,
        llcrnrlon=llon,
        llcrnrlat=llat,  #min longitude (llcrnrlon) and latitude (llcrnrlat)
        urcrnrlon=ulon,
        urcrnrlat=ulat)  #max longitude (urcrnrlon) and latitude (urcrnrlat)

    my_map.drawcoastlines()
    my_map.drawcountries()
    my_map.drawmapboundary()
    my_map.fillcontinents(color='white', alpha=0.3)
    my_map.shadedrelief()
    plt.pause(0.0001)
    plt.show()

    colors = plt.get_cmap('jet')(np.linspace(0.0, 1.0, clusterNum))

    while True:
        if q.empty():
            time.sleep(5)

        else:
            obj = q.get()
            d = [x[0][0] for x in obj]
            c = [x[1] for x in obj]
            data = np.array(d)
            pcolor = np.array(c)
            print(c)
            try:
                xs, ys = my_map(data[:, 0], data[:, 1])
                my_map.scatter(xs,
                               ys,
                               marker='o',
                               alpha=0.5,
                               color=colors[pcolor])
                plt.pause(0.0001)
                plt.draw()
                time.sleep(5)
            except IndexError:  # Empty array
                pass
Example #38
0
def testOneShot(ncfile):
    myCMEMSdata = xr.open_dataset(ncfile).resample(time='3H').reduce(np.mean)

    # time 
    lastDate =myCMEMSdata.time.values[myCMEMSdata.time.values.size-1]
    startDate = myCMEMSdata.time.values[0]

    print(startDate," - ", lastDate)
    print(myCMEMSdata.time.values.size)

    plt.figure(figsize=(20.48, 10.24))
    plt.clf()

    # projection, lat/lon extents and resolution of polygons to draw
    # resolutions: c - crude, l - low, i - intermediate, h - high, f - full
    map = Basemap(projection='merc', llcrnrlon=-10.,
                  llcrnrlat=30., urcrnrlon=36.5, urcrnrlat=46.)
    #map.etopo()
    map.shadedrelief(scale=0.65)


    X, Y = np.meshgrid(myCMEMSdata.longitude.values,
                       myCMEMSdata.latitude.values)
    x, y = map(X, Y)

    waveH = myCMEMSdata.VHM0.values
    wDir = myCMEMSdata.VMDR.values
    del myCMEMSdata
 

    my_cmap = plt.get_cmap('rainbow')
    onde = map.pcolormesh(x, y, waveH[0,:,:], cmap=my_cmap, norm=matplotlib.colors.LogNorm(vmin=0.07, vmax=4.,clip=True))
    
    #plt.colorbar();

    # waves direction
    # reduce arrows density (1 out of 15)
    yy = np.arange(0, y.shape[0], 15)
    xx = np.arange(0, x.shape[1], 15)
    points = np.meshgrid(yy,xx)

    wDir = wDir[0,:,:]
    
    map.quiver(x[points],y[points],np.cos(np.deg2rad(270-wDir[points])),np.sin(np.deg2rad(270-wDir[points])),
    	edgecolor='lightgray', minshaft=4,  width=0.007, headwidth=3., headlength=4., linewidth=.5)

    plt.show()
    plt.savefig("prova_s065.jpg", quality=75)
    plt.close()
Example #39
0
 def plotMap(self, shader=False):
     """Plot the map on the map axis"""
     self.a.cla()
     m = Basemap(width=7500000, height=4000000, projection='lcc',
                 resolution='c', lat_1=25., lat_2=35, lat_0=40, lon_0=-100., ax=self.a)
     if shader:
         m.shadedrelief(scale=0.1)
     m.drawcoastlines()
     m.drawcountries()
     m.drawstates()
     parallels = np.arange(0., 81, 10.)
     m.drawparallels(parallels, labels=[False, True, True, False])
     meridians = np.arange(10., 351., 20.)
     m.drawmeridians(meridians, labels=[True, False, False, True])
     self.m = m
def render_map(grb_file, llclat, llclon, urclat, urclon, altitude_layer):
    """Given a grb file, renders a jpg map on disk."""
    print('processing file %s ' % grb_file)
    grbs = pygrib.open(grb_file)
    data = grbs.select(name='Temperature')[altitude_layer]['values']
    plt.figure(figsize=(12, 12))

    # We don't like the way noaa aligns things. We like monotonic variations.
    data = realign_noaa_data(data)
    lonlat2temp = interpolate.interp2d(ALL_LONS, ALL_LATS, data, kind='linear')
    lats_interp = np.arange(llclat, urclat, 0.01)
    lons_interp = np.arange(llclon, urclon, 0.01)
    data_interp = lonlat2temp(lons_interp, lats_interp)
    # Size of the img to render in meters.
    width, height = width_height_from_bbox(llclat, llclon, urclat, urclon)
    m = Basemap(
        projection='cass',
        lat_ts=10,
        lat_0=(urclat + llclat) / 2,
        lon_0=(llclon + urclon) / 2,
        resolution='i',
        width=width,
        height=height)
    x, y = m(*np.meshgrid(lons_interp, lats_interp))

    # Draw plenty of fancy stuff
    m.drawstates()
    m.drawcountries()
    m.drawlsmask()
    m.drawrivers()
    m.drawcoastlines()
    m.shadedrelief()
    m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1])
    m.pcolormesh(
        x,
        y,
        data_interp,
        shading='flat',
        cmap=plt.cm.jet,
        alpha=0.05,
        vmin=260,
        vmax=305)
    m.colorbar(location='right')
    plt.title('Temperature')
    image = '%s.jpg' % grb_file
    plt.savefig(image)
    plt.close()
def globe_tweet(rot=0,time=0):
    m = Basemap(projection='ortho', lon_0=rot, lat_0=20, resolution='c')
    m.shadedrelief(scale=0.1)
    m.drawcoastlines(color='0.4')
    m.drawcountries(color='0.4')
    m.fillcontinents(color='white',lake_color='gray')
    m.drawparallels(np.arange(-90.,91.,30.))
    m.drawmeridians(np.arange(0., 360., 60.))
    m.drawmapboundary(fill_color='0.8')

    lon=t_lon[time]
    lat=t_lat[time]

    x,y=m(lon,lat)
    m.plot(x,y,'bo',markersize=9)
    plt.show()
Example #42
0
def plot_cities():
    path = "/Users/richard/classes/294-1/project/sql/meta_cities.txt"
    city_coords = load_city_coords(path)
    coords = city_coords.values()

    m = Basemap(projection='mill',
            llcrnrlon=70. ,llcrnrlat=20,
            urcrnrlon=135. ,urcrnrlat=53.)

    m.drawcountries()
    m.shadedrelief()

    unzipped = [list(t) for t in zip(*coords)]
    lat, lon = unzipped[0], unzipped[1]
    x, y = m(lon, lat)
    m.scatter(x,y,s=25)
    plt.show()
Example #43
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 draw_map(outfilename, dpi, lllat, lllon, urlat, urlon):
    enlarge_by = 0.1
    plt.figure(num=None, figsize=(48, 48), dpi=dpi, facecolor='w', edgecolor='k')
    bmap = Basemap(projection='cyl', resolution='l',
                   lon_0=0.0,
                   lat_0=90.0, lat_ts=0.0,
                   llcrnrlat=lllat,
                   llcrnrlon=lllon,
                   urcrnrlat=urlat,
                   urcrnrlon=urlon)
    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)
    if outfilename:
        plt.savefig(outfilename, dpi='figure')
    else:
        plt.show()
Example #45
0
def plot(text, size):
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt
    #from matplotlib.font_manager import FontProperties
    
    #fontP = FontProPerties()
    #fontP.set_size('small')
    # setup Lambert Conformal basemap.
    m = Basemap(width=3000000,height=3000000,projection='lcc',
                resolution='c',lat_0=18,lon_0=78)
    m.drawcoastlines()
    #m.fillcontinents(color='coral',lake_color='aqua')
    m.shadedrelief()
    colors = numpy.random.rand(30,3)
    #lengend
    handles = []
    for i in range(30):
        patch = matpatch.Patch(color = colors[i], label='Topic ' + str(i+1))
        handles.append(patch)
    plt.legend(handles = handles,  bbox_to_anchor=(1.2, 1.0),  prop={'size':10})
    lat = [17.38,13.08,12.98,19.07,22.57,26.84,26.91,28.63,21.15,22.72,27.16,21.66,26.02,9.92]
    lon = [78.49,80.28,77.61,72.88,88.34,80.95,75.78,77.25,79.08,75.86,78.01,83.59,73.85,78.12]
    df_x = [0.35,-0.25,-0.35,0.25,0]
    df_y = [0.35,0.25,-0.25,-02.5,0]
    f_lat = []
    f_lon = []
    f_size = []
    f_color = []
    random.seed()
    for place_id in range(len(lat)):
        for i in range(5):
            #f_lat.append(lat[place_id] + df_y[i])
            f_lat.append(lat[place_id] + 3*(random.random()-0.5))
            f_lon.append(lon[place_id] + 3*(random.random()-0.5))
            #f_lon.append(lon[place_id] + df_x[i])
            f_size.append(size[place_id][i]*15)
            f_color.append(colors[text[place_id][i]])
            #m.plot(lon[place_id]+df_y[i],lat[place_id]+ df_x[i], 'bo',markersize = size[place_id][i], latlon = True)
    m.scatter(f_lon, f_lat, s = f_size, c = f_color, alpha = 0.5, latlon = True)
    m.scatter(lon, lat, s = 8000, c = 'b', alpha = 0.1, latlon = True)
    #m.scatter(f_lon, f_lat, s = f_size, c = f_color, latlon = True)
    #m.plot(f_lon,f_lat,'bo',markersize = 5, latlon = True)
    plt.show()
def data_plotting(q):
    plt.ion() # Interactive mode
    llon = -130
    ulon = 100
    llat = -30
    ulat = 60
    rcParams['figure.figsize'] = (14,10)
    my_map = Basemap(projection='merc',
                resolution = 'l', area_thresh = 1000.0,
                llcrnrlon=llon, llcrnrlat=llat, #min longitude (llcrnrlon) and latitude (llcrnrlat)
                urcrnrlon=ulon, urcrnrlat=ulat) #max longitude (urcrnrlon) and latitude (urcrnrlat)

    my_map.drawcoastlines()
    my_map.drawcountries()
    my_map.drawmapboundary()
    my_map.fillcontinents(color = 'white', alpha = 0.3)
    my_map.shadedrelief()
    plt.pause(0.0001)
    plt.show()


    colors = plt.get_cmap('jet')(np.linspace(0.0, 1.0, clusterNum))

    while True:
        if q.empty():
            time.sleep(5)

        else:
            obj=q.get()
            d=[x[0][0] for x in obj]
            c=[x[1] for x in obj]
            data = np.array(d)
            pcolor=np.array(c)
            print(c)
            try:
                xs,ys = my_map(data[:, 0], data[:, 1])
                my_map.scatter(xs, ys,  marker='o', alpha = 0.5,color=colors[pcolor])
                plt.pause(0.0001)
                plt.draw()
                time.sleep(5)
            except IndexError: # Empty array
                pass
Example #47
0
def show_coord_topo_turbine(turbine, show = True):
    """Plot the topology of a turbine

    Topographic Map with farms
    see: http://matplotlib.org/basemap/users/examples.html
    Basemap

    Parameters
    ----------
    turbine : Turbine
               The given turbine to show the topology.
    """

    radius = 20
    coord = [0.0, 0.0]
    coord[0] = np.float64(turbine.latitude)
    coord[1] = np.float64(turbine.longitude)

    graddiff = (radius/111.0) + 0.5  # degree in km

    m = Basemap(projection='stere', lon_0=coord[1], lat_0=coord[0],\
        llcrnrlon = coord[1]-graddiff, llcrnrlat = coord[0]-graddiff ,\
        urcrnrlon = coord[1]+graddiff, urcrnrlat = coord[0]+graddiff ,\
        rsphere=6371200., resolution = 'l', area_thresh=1000)

    # Target
    x_turbine,y_turbine = m(coord[1],coord[0])

    # labels = [left,right,top,bottom]
    parallels = np.arange(int(coord[0]-3), int(coord[0]+3), 1.)
    m.drawparallels(parallels,labels=[False,True,True,False])
    meridians = np.arange(int(coord[1]-3), int(coord[1]+3), 1.)
    m.drawmeridians(meridians,labels=[True,False,False,True])

    # plot farms in the radius
    m.plot(x_turbine, y_turbine, 'bo')
    m.shadedrelief()

    plt.title("Topography around a Turbine")

    if(show):
        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')
Example #49
0
def draw_map(filenames, outfilename, dpi, labels_col, title):
    data = read_files(filenames)
    enlarge_by = 0.1
    plt.figure(num=None, figsize=(72, 48), 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)
    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 outfilename:
            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 outfilename:
        plt.savefig(outfilename, dpi='figure')
    else:
        plt.show()
Example #50
0
 def _create_blank_map(self):
     # Lambert conformal basemap
     # lat_1 is first standard parallel.
     # lat_2 is second standard parallel (defaults to lat_1).
     # lon_0,lat_0 is central point.
     # rsphere=(6378137.00,6356752.3142) specifies WGS4 ellipsoid
     # area_thresh=1000 means don't plot coastline features less
     # than 1000 km^2 in area.
     m = Basemap(width=5000000,
                 height=5000000,
                 rsphere=(6378137.00,6356752.3142),
                 resolution='h',
                 area_thresh=1000.,
                 projection='lcc',
                 lat_1=-67,
                 lat_0=-70,
                 lon_0=-68.)
     # Draw parallels and meridians.
     m.drawparallels(np.arange(-80.,81.,10.))
     m.drawmeridians(np.arange(-180.,181.,20.))
     m.shadedrelief()
     return m
Example #51
0
def plot_tweets(lat=[0], long=[0], text='', heat=False):
    plt.style.use('ggplot')
    lon_0 = -125 #further west if negative, further east if not
    lon_1 = -66
    lat_0 = 25
    lat_1 = 52
    # create figure and axes instances
    plt.clf()
    dim = 6
    fig = plt.figure(figsize=(dim,(225/494)*dim))
    #ax = fig.add_subplot(111)
    ax = fig.add_axes([0,0 ,1,1])
    # create polar stereographic Basemap instance.
    m = Basemap(llcrnrlat=lat_0,urcrnrlat=lat_1, llcrnrlon=lon_0, urcrnrlon=lon_1, resolution='l')
    m.drawcoastlines()
    m.drawcountries()
    if random.random() > 0.5: 
        m.fillcontinents(color='tan')
    elif random.random() > 0.5: 
        m.bluemarble()
    elif random.random() > 0.5: 
        m.shadedrelief()
    elif random.random() > 0.5: 
        m.etopo()
    elif random.random() > 0.5: 
        m.drawmapboundary(fill_color='aqua')
    if heat:
        for i, l in enumerate(lat):
            lat[i] = lat[i] + random.random()*0.1
            long[i] = long[i] + random.random()*0.1
            p = ax.plot(long, lat, 'p')
    else:
        p = ax.plot(long, lat, 'p')
    if text is not None:
        for i, ht in enumerate(text):
            if len(lat) > i:
                ax.annotate(ht, (long[i], lat[i]), rotation=random.random()*45.)
    plt.savefig('/tmp/twitmap.png')
Example #52
0
def geramapa(star, data, title, labelx, nameimg, mapstyle='1', resolution='l', centermap=None, lats=None, erro=None, ring=None, atm=None, clat=None, sitearq=None, fmt='png', dpi=100, mapsize=None, cpoints=60, off=0):
    lon = star.ra - data.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation(lon.value, star.dec.value)
    if not centermap == None:
        center_map = EarthLocation(centermap[0],centermap[1])
    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution)
#    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.)
#    kx = fig.add_axes([-0.003,-0.001,1.006,1.002])
#    kx.set_rasterization_zorder(1)
    m.nightshade(data.datetime, alpha=0.3, zorder=0.5)  ## desenha a sombra da noite
    m.drawcoastlines(linewidth=0.5)  ## desenha as linhas da costa
    m.drawcountries(linewidth=0.5)  ## desenha os paises
    m.drawstates(linewidth=0.5)    ## Desenha os estados
    m.drawmeridians(np.arange(0,360,30))  ## desenha os meridianos
    m.drawparallels(np.arange(-90,90,30))  ## desenha os paralelos
    m.drawmapboundary()  ## desenha o contorno do mapa
    style = {'1': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'blue', 'rncolor':'blue', 'atcolor':'blue', 'outcolor':'red'},
             '2': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '3': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '4': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '5': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}}
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
    elif mapstyle == '3':
        m.shadedrelief()
    elif mapstyle == '4':
        m.bluemarble()
    elif mapstyle == '5':
        m.etopo()
    if not lats == None:
        xs, ys = m(lats[0], lats[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['lncolor'])
        xt, yt = m(lats[2], lats[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['lncolor'])
        m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=-0.2)
        m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=-0.2)
#    else:
#        m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
#        m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
    if not erro == None:
        xs, ys = m(erro[0], erro[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['ercolor'])
        xt, yt = m(erro[2], erro[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['ercolor'])
    if not ring == None:
        xs, ys = m(ring[0], ring[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['rncolor'])
        xt, yt = m(ring[2], ring[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['rncolor'])
    if not atm == None:
        xs, ys = m(atm[0], atm[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['atcolor'])
        xt, yt = m(atm[2], atm[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['atcolor'])
    if not clat == None:
        xc, yc, lab = [], [], []
        cp = Time(clat[5], format='iso')
        vec = np.arange(0, (cp[-1] - data).sec, cpoints)
        vec = np.sort(np.concatenate((vec,-vec[1:]), axis=0))*u.s
        for i in vec:
            g = data + TimeDelta(i) + TimeDelta(off*u.s)
            if g.iso in clat[2]:
                a = np.where(np.array(clat[2]) == g.iso)
                x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                xc.append(x)
                yc.append(y)
                lab.append(g.iso.split()[1][0:8])
            elif g.iso in clat[5]:
                a = np.where(np.array(clat[5]) == g.iso)
                xc.append(np.array(clat[3])[a])
                yc.append(np.array(clat[4])[a])
                lab.append(g.iso.split()[1][0:8])
            else:
                if len(clat[2]) == 0:
                    a = [0]
                else:
                    co = Time(clat[2], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                if 0 not in a and len(co)-1 not in a:
                    b = np.absolute((co[a] - g).sec)
                    x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                    xc.append(np.sum(x*(1/b))/np.sum(1/b))
                    yc.append(np.sum(y*(1/b))/np.sum(1/b))
                    lab.append(g.iso.split()[1][0:8])
                else:
                    co = Time(clat[5], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                    b = np.absolute((co[a] - g).sec)
                    xc.append(np.sum(np.array(clat[3])[a]*(1/b))/np.sum(1/b))
                    yc.append(np.sum(np.array(clat[4])[a]*(1/b))/np.sum(1/b))
                    lab.append(g.iso.split()[1][0:8])
        m.plot(xc, yc, 'o', color=style[mapstyle]['ptcolor'], clip_on=False, markersize=mapsize[0].value*8/46)
        m.plot(clat[6][0], clat[6][1], 'o', color=style[mapstyle]['ptcolor'], clip_on=False, markersize=mapsize[0].value*20/46)

#    for label, axpt, bypt in zip(lab, xc, yc):
#        plt.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')




#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color='red')
#    m.plot(ax4.to(u.m), by4.to(u.m), color='red')
#    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')

#    if os.path.isfile(sitearq) == True:
#        xpt,ypt = m(sites['lon'],sites['lat'])
#        m.plot(xpt,ypt,'bo')
#        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
#        for i in np.arange(len(xpt)):
#            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)



    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
    plt.title(title, fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
    plt.xlabel(labelx, fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
    plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi)
    print 'Gerado: {}.{}'.format(nameimg, fmt)
    plt.clf()
Example #53
0
#tot_sp_int1.plot(title='Country Sample counts by interface and sampling date', figsize=(12, 10), lw=2)

# <markdowncell>

# ## Sampling sites: Africa

# <codecell>

#AFRICA
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
# setup Lambert Conformal basemap.
# set resolution=None to skip processing of boundary datasets.
fig = plt.figure(figsize=(12,12))
m = Basemap(width=12000000,height=10000000,projection='lcc', resolution=None,lat_1=25.,lat_2=55,lat_0=0,lon_0=20.)
m.shadedrelief()
lon, lat = 0, 0
xpt,ypt = m(frame['Longitude'],frame['Latitude'])
m.plot(xpt,ypt,'bo')
plt.show()

# <markdowncell>

# ## Sampling Sites: South America

# <codecell>

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
# setup Lambert Conformal basemap.
# set resolution=None to skip processing of boundary datasets.
Example #54
0
def draw(args):
    
    # draw Basemap
    lat_0 = (args.llcrnrlat+args.urcrnrlat)/2
    lon_0 = (args.llcrnrlon+args.urcrnrlon)/2
    m = Basemap(
        projection=projection, resolution = 'l',
        lat_0=lat_0, lon_0=lon_0,
        llcrnrlon=args.llcrnrlon, llcrnrlat=args.llcrnrlat,
        urcrnrlon=args.urcrnrlon, urcrnrlat=args.urcrnrlat,
        )
    m.drawcoastlines()
    m.drawcountries()
    if args.mapbackground == 'bluemarble':
        m.bluemarble()
    elif args.mapbackground == 'fillcontinents':
        m.fillcontinents(color = args.fillcontinents_color)
    elif args.mapbackground == 'etopo':
        m.etopo()
    elif args.mapbackground == 'shadedrelief':
        m.shadedrelief()
    m.drawmapboundary()
    if args.drawmeridians:
        m.drawmeridians(np.arange(0, 360, 1), labels=[1, 1, 1, 1], fontsize='xx-small')
    if args.drawparallels:
        m.drawparallels(np.arange(-90, 90, 1), labels=[1, 1, 1, 1], fontsize='xx-small')

    l_colors_VGA16 = (
        (1,0,0), # red
        (0,1,0), # green/lime
        (0,0,1), # blue
        (0,1,1), # cyan/aqua
        (1,0,1), # magenta/fuchsia
        (1,1,0), # yellow
        (1,.5,0), # orange
        (1,1,1), # white
    #    '#800000', # maroon
        '#800080', # purple
    #    '#008000', # dark green
    #    '#808000', # olive
        '#000080', # navy
        '#008080', # teal
        (0,0,0), # black
        '#808080', # dark grey / silver?
        '#C0C0C0', # light grey / silver?
    #    (.5,1,0), # green yellow
        (0,1,.5), # green cyan
        (0,.5,1), # blue cyan
        (.5,0,1), # blue magenta
        (1,0,.5), # red magenta
        (1,.5,.5), ## red?
        (.5,1,.5), ## green?
        (.5,.5,1), ## blue?
        )
    l_colors_colorbrewer = [
            (166,206,227),
            (31,120,180),
            (178,223,138),
            (51,160,44),
            (251,154,153),
            (227,26,28),
            (253,191,111),
            (255,127,0),
            (202,178,214),
            (106,61,154),
            (255,255,153),
            (177,89,40),
            ]
    for i, color in enumerate(l_colors_colorbrewer):
        l_colors_colorbrewer[i] = (l_colors_colorbrewer[i][0]/255,l_colors_colorbrewer[i][1]/255,l_colors_colorbrewer[i][2]/255)

##    ## https://docs.python.org/3/library/colorsys.html
##    l_colors = [(1,1,1),'#808080','#C0C0C0']+[Color(hue=h/360., saturation=1, luminance=.5).rgb for h in range(0,360,int(360/10))]
    l_colors = [(1,1,1),'#808080','#C0C0C0']+l_colors_colorbrewer
    l_colors = l_colors+l_colors
#    l_colors = l_colors_VGA16
#    l_colors = ['#f1a340', '#998ec3']  # colorbrewer2.org, 3 data classes, diverging, scheme 4
#    l_colors = ['#e41a1c', '#984ea3']  # colorbrewer2.org, 4 data classes, qualitative, scheme 6
#    l_colors = ['#d01c8b', '#4dac26']  # colorbrewer2.org, 4 data classes, diverging, scheme 2
#    l_colors = ['#e41a1c', '#4daf4a']
#    l_colors = ['rgb(27,158,119)','rgb(217,95,2)','rgb(117,112,179)','rgb(231,41,138)','rgb(102,166,30)']  # 5 classes, qual, scheme 2
#    l_colors = ['rgb(27,158,119)','rgb(217,95,2)','rgb(117,112,179)','rgb(231,41,138)','rgb(102,166,30)','rgb(230,171,2)']
#    l_colors = ['rgb(27,158,119)','rgb(217,95,2)','rgb(117,112,179)','rgb(231,41,138)','rgb(102,166,30)','rgb(230,171,2)','rgb(166,118,29)']
#    l_colors = ['rgb(228,26,28)','rgb(55,126,184)','rgb(77,175,74)','rgb(152,78,163)','rgb(255,127,0)','rgb(255,255,51)','rgb(166,86,40)']
#    l_colors_blue = ['rgb(222,235,247)','rgb(158,202,225)','rgb(49,130,189)']  # 3, sequential, single hue 1 (blue)
#    l_colors_green = ['rgb(229,245,224)','rgb(161,217,155)','rgb(49,163,84)']  # 3, seq, single hue 2 (green)
#    l_colors_orange = ['rgb(254,230,206)','rgb(253,174,107)','rgb(230,85,13)']  # 3, seq, single hue 4 (orange)
#    l_colors_red = ['rgb(254,224,210)','rgb(252,146,114)','rgb(222,45,38)']  # 3, seq, single hue 6 (red)
#    l_colors = [l_colors_red[0], l_colors_red[2], l_colors_green[0], l_colors_green[2], l_colors_blue[0], l_colors_blue[2],]
#    l_colors = [l_colors_red[0], l_colors_red[2], l_colors_green[0], l_colors_green[2], l_colors_blue[2],]
#    l_colors = [tuple(int(i)/255 for i in color[4:-1].split(',')) for color in l_colors]  # tmp!!! for colorbrewer2.org export
#    ## 4, qual, colorblind safe
#    l_colors = ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c']
    ## 9, qual, printer friendly (4,5,6,7,8 are subsets)
    l_colors = [
        '#e41a1c', '#377eb8', '#4daf4a',
        '#984ea3', '#ff7f00', '#ffff33',
        '#a65628', '#f781bf', '#999999',
        ]

    l_markerstyles = ['o','s','^','v','*','D','p']

#    for i, color in enumerate(l_colors_colorbrewer):
#        l_colors_colorbrewer[i] = (l_colors_colorbrewer[i][0]/255,l_colors_colorbrewer[i][1]/255,l_colors_colorbrewer[i][2]/255)

    if args.colorlist:
        l_colors = ['#{}'.format(color) for color in args.colorlist]

    with open(args.input_file) as f:
        lines = f.readlines()

    d_colors = {}
    d_markerstyles = {}

    set_labels = set()
    for line in lines:

        ## skip blank lines
        if not line.strip():
            continue
        ## skip comment lines
        if line[0] == '#':
            continue
        ## split line into list of column fields
        l = line.rstrip().split('\t')

        ## parse values from line
        lat = float(l[args.lat])
        lon = float(l[args.lon])
        label = l[args.labels]
        text = l[args.text]

        ## tmp!!!
        try:
                label = {
#                    '1': 'REC approval, SEQUENCED',
#                    '2': 'REC approval, SEQUENCING',
                    '1': 'Sequenced/Sequencing',
                    '2': 'Sequenced/Sequencing',
#                    '3': 'REC approval, OTHERS',
#                    '5': 'EXISTING STUDIES NOT YET APPROVED',
                    '3': 'Other collections, Approved',
                    '5': 'Other collections, Not yet approved',
#                    '4': 'NEW COLLECTIONS',
                    '4': 'Planned collections',
                    'MENTOR': 'MENTOR Initiative',
#                    '6': '1000G phase 3',
                    '6': 'Sequenced/Sequencing',
                    }[label]
        except:
            pass

        ## markersize
        if args.markersize:
            if l[args.markersize] != 'NA':
                markersize = float(l[args.markersize])
            else:
                markersize = 10
        else:
            markersize = 10
        if args.log:
            markersize = cnt2markersize(markersize)

        ## markerstyle
        if args.markerstyle:
            try:
                markerstyle = d_markerstyles[l[args.markerstyle]]
            except KeyError:
                markerstyle = l_markerstyles[len(list(d_markerstyles.keys()))]
                d_markerstyles[l[args.markerstyle]] = markerstyle
        else:
            markerstyle = 'o'

        ## color
        if args.colors:
            color = l[args.colors]
        elif args.markerfacecolor:
            color = args.markerfacecolor
        else:
            try:
                color = d_colors[label]
            except KeyError:
                color = l_colors[len(list(d_colors.keys()))]
                d_colors[label] = color

        ## convert lon and lat to x and y
        x, y = m(lon, lat)
        if args.offsetx and args.offsety:
            offset_extra = (float(l[args.offsetx]), float(l[args.offsety]))
        else:
            offset_extra = (0, 0)
        ## get text position
        x_text, y_text = m(lon+offset_extra[0], lat+args.offset+offset_extra[1])
        if args.no_text_labels == False:
            text = plt.text(
                x_text, y_text, text.replace('\\n','\n'),
                horizontalalignment='center', size=args.text_size,
                color=color)
            text.set_path_effects([
                path_effects.Stroke(linewidth=2, foreground='black'),
                path_effects.Normal()])
        ## plot data point
        m.plot(
            x, y, markerstyle, markersize=markersize, markerfacecolor=color, label="")
        ## plot outside map to have label appear (not very elegant solution...)
        x, y = m(-60, -60)
        if not label in set_labels:
            set_labels.add(label)
            m.plot(x, y, 'o', markersize=10, markerfacecolor=color, label=label)

    if args.markersize:
#        for i in range(1,3):
        for i in range(0,3): # make this log dependent and input range dependent...
            m.plot(
                x, y, 'o', markersize=cnt2markersize(pow(10, i)),
                markerfacecolor='white', label=pow(10, i))

    if args.markerstyle:
        for label, markerstyle in sorted(d_markerstyles.items()):
            m.plot(
                x, y, markerstyle, markersize=cnt2markersize(10),
                markerfacecolor='white', label='Sequencing depth of coverage '+label)

    distance_from_plot = 0.05
    print('ncol', args.ncol)
    plt.legend(
        ncol=args.ncol, shadow=True,
##        prop={'size':8.5},
        prop={'size':6.5},
        numpoints=1,
        labelspacing=1.0,
        loc=args.loc,
        fancybox=True,
##        handleheight=2.5,
        borderpad=0.7,
        framealpha=0.5,
        )

    if args.out:
        out = '{}.jpg'.format(args.out)
    else:
        out = '{}_{}_{}.jpg'.format(
            os.path.splitext(os.path.basename(args.input_file))[0], projection, args.mapbackground)
    plt.savefig(out, dpi=args.dpi)

    plt.title('{} {} {}'.format(
            getpass.getuser(),
            '.'.join(platform.node().split('.')[1:]),
            time.strftime('%a %Y%b%d', time.gmtime())))

    plt.close()

    return
Example #55
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
Example #56
0
def show_flip_book(windpark, num_plots, start_time, diff_time, show=True):
    """Plots a flip book of a given windpark

    Parameters
    ----------
    windpark : Windpark
               The windpark for the flip book.

    num_plots: int
               Amount of plots, either 4, 9 or 16.

    start_time: int
                Element position of time series.

    diff_time: int
               Temporal distance between plots.
    """

    turbines = windpark.get_turbines()
    target = windpark.get_target()
    radius = windpark.get_radius()

    number_of_plots = num_plots
    start_measurement = start_time
    time_diff_between_plot = diff_time

    #pack latitude and longitude in lists
    rel_input_lat = []
    rel_input_lon = []
    rel_input_speed_array = [[0 for col in range(number_of_plots)] for row in range(len(turbines))]

    # For labeling the plot with a timestamp
    unix_timestamps = []
    timestamps_known = 0

    row_act = 0
    for row in turbines:   # Target inside !!!!
        rel_input_lat.append(np.float64(row.latitude))
        rel_input_lon.append(np.float64(row.longitude))
        time = start_measurement
        for measurement in range(number_of_plots):
            rel_input_speed_array[row_act][measurement] = row.measurements[time][2]
            time += time_diff_between_plot

        if (timestamps_known == 0):
            time = start_measurement
            for measurement in range(number_of_plots):
                unix_timestamps.append(row.measurements[time][0])
                time += time_diff_between_plot
            timestamps_known = 1

        row_act += 1

    targetcoord = [0.0, 0.0]
    targetcoord[0] = np.float64(target.latitude)
    targetcoord[1] = np.float64(target.longitude)

    # Topographic Map with farms
    #see: http://matplotlib.org/basemap/users/examples.html
    # Basemap
    graddiff = (radius/111.0) + 0.1  # degree in km

    m = Basemap(projection='stere', lon_0=targetcoord[1], lat_0=targetcoord[0],\
        llcrnrlon = targetcoord[1]-graddiff, llcrnrlat = targetcoord[0]-graddiff ,\
        urcrnrlon = targetcoord[1]+graddiff, urcrnrlat = targetcoord[0]+graddiff ,\
        rsphere=6371200., resolution = 'l', area_thresh=1000)

    # Target
    #x_target,y_target = m(targetcoord[1],targetcoord[0])
    # Input Farms
    rel_inputs_lon, rel_inputs_lat = m(rel_input_lon, rel_input_lat)

    plot_dim = math.sqrt(number_of_plots)
    figure = plt.figure(figsize=(15, 10))
    plt.title("Flip - Book")
    for i in range(1, (number_of_plots+1)):
        plot = plt.subplot(plot_dim, plot_dim, i)
        zlist = []
        for z in range(len(turbines)):
            zlist.append(rel_input_speed_array[z][i-1])
        parallels = np.arange(int(targetcoord[0]-3), int(targetcoord[0]+3), 1.)
        m.drawparallels(parallels,labels=[True,False,False,False])
        meridians = np.arange(int(targetcoord[1]-3), int(targetcoord[1]+3), 1.)
        m.drawmeridians(meridians,labels=[True,False,False,True])
        m.shadedrelief()
        m.drawcoastlines
        m.scatter(rel_inputs_lon, rel_inputs_lat, c = zlist, s = 35, vmin = 0.0, vmax = 35)
        plt.title(datetime.datetime.fromtimestamp(unix_timestamps[i-1]).strftime('%Y-%m-%d %H:%M:%S'))
        plt.colorbar()

    if(show):
        plt.show()
Example #57
0
def geramapa(delt):
    deltatime = delt*u.s
    datas1 = datas[idx] + TimeDelta(deltatime)
    datas1.delta_ut1_utc = 0
    lon = stars[idx].ra - datas1.sidereal_time('mean', 'greenwich')

    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution)
#    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution, llcrnrx=-7000000,llcrnry=-7000000,urcrnrx=7000000,urcrnry=7000000)
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.drawstates(linewidth=0.5)
    m.drawmeridians(np.arange(0,360,30))
    m.drawparallels(np.arange(-90,90,30))
    m.drawmapboundary()
    ptcolor = 'black'
    lncolor = 'black'
    dscolor = 'black'
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '3':
        m.shadedrelief()
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '4':
        m.bluemarble()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    elif mapstyle == '5':
        m.etopo()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    if os.path.isfile(sitearq) == True:
        xpt,ypt = m(sites['lon'],sites['lat'])
        m.plot(xpt,ypt,'bo')
    CS=m.nightshade(datas1.datetime, alpha=0.2)
    a, b =m(lon.value, stars[idx].dec.value)
    a = a*u.m
    b = b*u.m
    dista = (dist[idx].to(u.km)*ca[idx].to(u.rad)).value*u.km
    disterr = (dist[idx].to(u.km)*erro.to(u.rad)).value*u.km
    ax = a + dista*np.sin(pa[idx]) + (deltatime*vel[idx])*np.cos(pa[idx])
    by = b + dista*np.cos(pa[idx]) - (deltatime*vel[idx])*np.sin(pa[idx])
    m.plot(ax,by, 'o', color=ptcolor, markersize=mapsize[0].value*20/46)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
    plt.title('-{} D={}- dots each 60 s <> offsets (mas): obj=({:.1f},{:.1f}), star=({:.1f},{:.1f})\n'
        .format(obj, tamanho, ob_off_ra[idx].value, ob_off_de[idx].value, st_off_ra[idx].value, st_off_de[idx].value), fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
    plt.xlabel('\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta   R*   K*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f}  {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
        .format(datas1.iso, int(stars[idx].ra.hms.h), int(stars[idx].ra.hms.m), stars[idx].ra.hms.s, int(stars[idx].dec.dms.d), np.absolute(int(stars[idx].dec.dms.m)), np.absolute(stars[idx].dec.dms.s),
        ca[idx].value, pa[idx].value, vel[idx].value, dist[idx].value, magR[idx], magK[idx], longi[idx]), fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
    plt.savefig('{}_{:05d}.png'.format(obj, np.where(g==delt)[0][0] + 1),dpi=100)
    print 'Gerado: {}_{:05d}.png'.format(obj, np.where(g==delt)[0][0] + 1)
    plt.clf()
Example #58
0
def mapping(states, targetCounties, minVal, maxVal, clientName, outPath, shapePathRoot):

    # shapePathRoot = 'C:\\Python27\\Lib\\site-packages\\mpl_toolkits\\basemap\\data\\'

    countyShapeName = 'cb_2014_us_county_500k'
    # countyShapeName = 'UScounties'

    shapePathCounty = manageShapeFile(shapePathRoot, countyShapeName)
    # print shapePathCounty
    # testShape = shapefile.Reader(shapePathCounty)

    stateShapeName = 'cb_2014_us_state_500k'
    shapePathState = manageShapeFile(shapePathRoot, stateShapeName)
    stateShape = shapefile.Reader(shapePathState)

    f = open('state_codes.csv','rb')
    rdr = csv.reader(f)
    rdr.next()
    stateLookup = {i[2].zfill(2):i[1] for i in rdr}
    codeLookup = {stateLookup[i]:i for i in stateLookup.keys()}
    exStates = ['AK','HI']
    stateCodes = [codeLookup[i] for i in states if i not in exStates]
    exCodes = [i for i in states if i  in exStates]
    print 'getting boundaries and excluding', exCodes
    minLat, minLon, maxLat, maxLon = getBoundaries(shapePathCounty, targetCounties, stateCodes)

    fig = plt.figure()
    # axes: left, bottom, width, height

    ax1 = plt.subplot(111)

    print 'coordinate boundaries', minLat, minLon, maxLat, maxLon
    centerLat = (minLat + maxLat) / 2
    centerLon = (minLon + maxLon) / 2
    lats = [minLat, maxLat, centerLat]
    lons = [minLon, maxLon, centerLon]
    cords = list(itertools.chain.from_iterable([[(i,j) for i in lons] for j in lats]))

    convCords = []
    # convert the midpoint lat and min lon to coordiantes and make the x of that the lower corner

    map = Basemap(llcrnrlon=minLon-2,llcrnrlat=minLat-2,urcrnrlon=maxLon,urcrnrlat=maxLat,
                  projection='stere', resolution='l',lat_0=centerLat, lon_0=centerLon, lat_ts=minLat)
    # draw coastlines, country boundaries, fill continents.
    for cord in cords:
      convCords.append(map(cord[0],cord[1]))
    
    convCordsAr = np.array(convCords)
    #print convCordsAr
    mins = np.amin(convCordsAr,axis=1)
    maxes = np.amax(convCordsAr,axis=1)
    xmin = mins[0]
    xmax = maxes[0]
    ymin = mins[1]
    ymax = maxes[1]

    map = Basemap(llcrnrlon=minLon-2,llcrnrlat=minLat-2,urcrnrlon=maxLon,urcrnrlat=maxLat,
                  projection='stere', resolution='l',lat_0=centerLat, lon_0=centerLon, lat_ts=minLat,
                  width=xmax-xmin, height=ymax-ymin)

    map.drawcoastlines(linewidth=0.25)
    map.drawcountries(linewidth=0.25)
    #map.fillcontinents(color=(.8,.8,.8), lake_color='aqua')
    #map.fillcontinents(lake_color='aqua')
    #map.drawstates(linewidth=4)
    map.shadedrelief()
    #map.drawcounties(linewidth=.1)


    map.readshapefile(shapePathCounty, 'counties', drawbounds=True)
    norm = mpl.colors.Normalize(vmin=minVal, vmax=maxVal, clip=False)
    cmap = cm.get_cmap(name='Reds')
    colMaker = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
    # info are the fields
    myCols = []
    for info, shape in zip(map.counties_info, map.counties):
        patches = []

        if stateLookup[info['STATEFP']] + '_' + info['NAME'] in targetCounties.keys():

            origValue = targetCounties[stateLookup[info['STATEFP']] + '_' + info['NAME']]

            col = colMaker.to_rgba(origValue)
            myCols.append(origValue)
            patches.append(Polygon(np.array(shape), closed=True, label=stateLookup[info['STATEFP']]))

            ptch = PatchCollection(patches, edgecolor='black', facecolor=col,
                                       linewidths=1., alpha=0.7)
            coll = ax1.add_collection(ptch)
    coll.set_array(np.array(myCols))

    #ptch.set_array(np.array(origValue))


    cbar = map.colorbar(coll, location='bottom', pad='5%', cmap='Reds')
    cbar.set_label('Location Value')
    #map.readshapefile(shapePathState, 'states', drawbounds=True, linewidth=1.5)
    #for info, shape in zip(map.states_info, map.states):
        #print info['NAME']
    #    if info['NAME'] == 'Florida':

            #outAr = np.array(shape)
            #np.savetxt('c:\\users\\dwright\\desktop\\' + info['NAME'] + 'testFile.csv',outAr, delimiter=',')
            #sys.exit()


    # I can also find the center of the county and name it!
    # will need to figure out eh size of the name

    # draw the edge of the map projection region (the projection limb)
    map.drawmapboundary(fill_color='aqua')
    # draw lat/lon grid lines every 30 degrees.

    title = 'Exposure Heatmap for {0}'.format(clientName)
    plt.title(title)
    outFileName = 'ExposureMap_{0}'.format(clientName)
    outPath = outPath + '{0}.jpg'.format(outFileName)

    plt.tight_layout()
    plt.savefig(outPath)
    #plt.show()
    plt.clf()

    return
Example #59
0
bmap.bluemarble()

# as above, but use shaded relief image as map background.
fig = plt.figure()
bmap.drawmapboundary()
bmap.drawmeridians(np.arange(0,360,30))
bmap.drawparallels(np.arange(-90,90,30))
# plot filled circles at the locations of the cities.
bmap.plot(xc,yc,'wo')
# plot the names of five cities.
for name,xpt,ypt in zip(cities,xc,yc):
    plt.text(xpt+50000,ypt+50000,name,fontsize=9,color='w')
# contour data over the map.
cs = bmap.contour(x,y,wave+mean,15,linewidths=1.5)
plt.title('shaded relief background')
bmap.shadedrelief()

# as above, but use etopo image as map background.
fig = plt.figure()
bmap.drawmapboundary()
bmap.drawmeridians(np.arange(0,360,30))
bmap.drawparallels(np.arange(-90,90,30))
# plot filled circles at the locations of the cities.
bmap.plot(xc,yc,'wo')
# plot the names of five cities.
for name,xpt,ypt in zip(cities,xc,yc):
    plt.text(xpt+50000,ypt+50000,name,fontsize=9,color='w')
# contour data over the map.
cs = bmap.contour(x,y,wave+mean,15,linewidths=1.5)
plt.title('etopo background')
bmap.etopo()
filename = 'vic_timing_frzsoil_5.txt'

# Set up the map
# lat_ts is the latitude of true scale.
# resolution = 'c' means use crude resolution coastlines.
# m = Basemap(projection='merc',llcrnrlat=-65,urcrnrlat=80,\
#            llcrnrlon=0,urcrnrlon=360,lat_ts=0,resolution='c')
m = Basemap(llcrnrlat=-89.5,urcrnrlat=89.5,\
            llcrnrlon=0.5,urcrnrlon=359.5,resolution='c')
#m.drawcoastlines(color='0.2')
m.drawcountries(color='0.4')
#m.fillcontinents(color='white',lake_color='zero')
#m.drawparallels(np.arange(-90.,91.,30.), labels=[1,0,0,1])
#m.drawmeridians(np.arange(0., 360., 60.), labels=[1,0,0,1])
m.drawmapboundary(fill_color='0.8')
m.shadedrelief(scale=0.1, origin='lower')

# Set up the color data
data = np.transpose(np.loadtxt(filename))
lat = data[0] 
lon = data[1]
mean_timing = data[2]

array = np.empty((180,360))
array[:] = np.NAN;

x = np.arange(0.5, 360.5, 1.0)
y = np.arange(-90.5, 89.5, 1.0)
x,y = np.meshgrid(x,y)
x,y = m(x,y)
print np.max(mean_timing)