Esempio n. 1
0
def addShape(shapefilename, lw=0.0):

    r = shapefile.Reader(shapefilename)
    shapes = r.shapes()
    records = r.records()

    cnt = 0
    for record, shape in zip(records, shapes):
        print(cnt)

        lons,lats = zip(*shape.points)
        data = np.array(m(lons, lats)).T

        if len(shape.parts) == 1:
            segs = [data,]
        else:
            segs = []
            for i in range(1,len(shape.parts)):
                index = shape.parts[i-1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
            segs.append(data[index2:])

        lines = LineCollection(segs,antialiaseds=(1,), zorder=3)
        lines.set_facecolors(np.random.rand(3, 1) * 0.5 + 0.5)
        lines.set_edgecolors('k')
        lines.set_linewidth(lw)
        ax.add_collection(lines)
        cnt += 1
Esempio n. 2
0
def add_data(globe, axes, color_dict):
    """Add shapefile polygons to the matplotlib axes"""
    file_object = shapefile.Reader(filename)
    shapes = file_object.shapes()
    records = file_object.records()
    #iterate over all but the first 20 polygons (they're junk)
    for record, shape in zip(records[20:],shapes[20:]):
        #this entry is the colour code
        description = record[6]
        lons,lats = zip(*shape.points)
        #transform the lat/long coords to the right projection
        data = np.array(globe(lons, lats)).T
        #shapefile shapes can have disconnected parts, we have
        #to check
        if len(shape.parts) == 1:
            segs = [data,]
        else:
            segs = []
            for i in range(1,len(shape.parts)):
                #add all the parts
                index = shape.parts[i-1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
            segs.append(data[index2:])
        #Add all the parts we've found as a set of lines
        lines = LineCollection(segs,antialiaseds=(1,))
        lines.set_facecolors(color_dict[description])
        lines.set_edgecolors('k')
        lines.set_linewidth(0.1)
        #add the collection to the active axes
        axes.add_collection(lines)
def plot_view(result):
    # Determine bounding box if no clipping boundary was supplied
    if not result['bbox']:
        result['bbox'] = bbox_of_view(result)

    ax = plt.subplot(111)
    # plt.box(on=None)
    m = Basemap(resolution='i',
                projection='merc',
                llcrnrlat=result['bbox']['ymin'],
                urcrnrlat=result['bbox']['ymax'],
                llcrnrlon=result['bbox']['xmin'],
                urcrnrlon=result['bbox']['xmax'],
                lat_ts=(result['bbox']['xmin'] +
                        result['bbox']['xmax']) / 2)
    m.drawcoastlines()

    try:
        for el in result['results']:
            vectors = get_vectors_from_postgis_map(m, loads(el['geom']))
            lines = LineCollection(vectors, antialiaseds=(1, ))
            lines.set_facecolors('black')
            lines.set_edgecolors('white')
            lines.set_linewidth(1)
            ax.add_collection(lines)
        m.fillcontinents(color='coral', lake_color='aqua')
    # If AttributeError assume geom_type 'Point', simply collect all
    # points and perform scatterplot
    except AttributeError:
        xy = m([loads(point['geom']).x for point in result['results']],
               [loads(point['geom']).y for point in result['results']])
        plt.scatter(xy[0], xy[1])

    plt.show()
Esempio n. 4
0
    def plot(self,
             ax=None,
             cmapname=None,
             cmap=None,
             linewidth=1,
             edgecolor='grey',
             facecolor=None,
             alpha=1):
        """Plot the geometries on the basemap using the defined colors

        Parameters:
        -----------
        ax : matplotlib.axis object
            An axis object for plots. Overwrites the self.ax attribute.
        cmapname : string
            Name of the color map from matplotlib (LINK!) (default: 'seismic')
        cmap : matplotlib colormap
            You can create you own colormap and pass it to the plot.
        linewidth : float
            Width of the lines.
        edgecolor : string, float or iterable
            Definition of the edge color. Can be an iterable with a color
            definition for each geometry, a string with one color for
            all geometries or a float to define one color for all geometries
            from the cmap.
        facecolor : string, float or iterable
            Definition of the face color. See edgecolor.
        alpha : float
            Level of transparency.
        """
        if ax is not None:
            self.ax = ax
        n = 0
        if facecolor is None:
            facecolor = self.color
        if edgecolor is None:
            edgecolor = self.color
        if cmapname is not None:
            self.cmapname = cmapname
        if self.data is not None:
            self.data = np.array(self.data)
        if cmap is None:
            cmap = plt.get_cmap(self.cmapname)
        for geo in self.geometries:
            vectors = self.get_vectors_from_postgis_map(geo)
            lines = LineCollection(vectors, antialiaseds=(1, ))
            lines.set_facecolors(self.select_color(facecolor, cmap, n))
            lines.set_edgecolors(self.select_color(edgecolor, cmap, n))
            lines.set_linewidth(linewidth)
            lines.set_alpha(alpha)
            self.ax.add_collection(lines)
            n += 1
def draw_map(dpts_dataframe, topic_index):
    m, ax = carte_france()

    departements = 'data/DEPARTEMENT/DEPARTEMENT.shp'
    shp = departements
    r = shapefile.Reader(shp)
    shapes = r.shapes()
    records = r.records()
    records = clean_records(records)
    done = False

    for record, shape in zip(records, shapes):
        geo_points = [lambert932WGPS(x, y) for x, y in shape.points]
        lons = [_[0] for _ in geo_points]
        lats = [_[1] for _ in geo_points]
        data = np.array(m(lons, lats)).T

        if len(shape.parts) == 1:
            segs = [
                data,
            ]
        else:
            # un polygone est une liste de sommets
            # on le transforme en une liste d'arêtes
            segs = []
            for i in range(1, len(shape.parts)):
                index = shape.parts[i - 1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
            segs.append(data[index2:])

        lines = LineCollection(segs, antialiaseds=(1, ))

        # pour changer les couleurs c'est ici, il faudra utiliser le champ records
        # pour les changer en fonction du nom du départements
        if not done:
            for i, _ in enumerate(record):
                print(i, _)
            done = True
    #    dep = retourne_vainqueur(record[2])
        dep = True
        if dep is not None:
            couleur = colors[int(dpts_dataframe['code_couleur'].loc[
                dpts_dataframe[0] == int(record[1])].values[0]), :]
            lines.set_facecolors(couleur)
            lines.set_edgecolors('k')
            lines.set_linewidth(0.1)
            ax.add_collection(lines)
        else:
            print("--- issue with", record[-1])
    plt.savefig('heatmaps/heatmap_topic' + str(topic_index) + '.png')
Esempio n. 6
0
def plot_countries(countries, world):
    if type(countries) != list:
        countries = [countries]
    ax = plt.subplot(111)
    m = get_region_map(countries, world)
    for country in countries:
        shpsegs = []
        for ring in country['SHAPE']:
            x, y = geo2map_coord(ring, m)
            shpsegs.append(zip(x,y))
        lines = LineCollection(shpsegs,antialiaseds=(1,))
        lines.set_facecolors(cm.jet(np.random.rand(1)))
        lines.set_edgecolors('k')
        #lines.set_linewidth(0.3)
        ax.add_collection(lines)
    plt.show()
Esempio n. 7
0
def drawShape(m, ax, paraTable):
    for conshpfn in paraTable["ShapeFile"].unique():
        for i, conShape in enumerate(getPointArray(conshpfn)):
            tempParaTable = concat([paraTable[paraTable["ShapeFile"]==conshpfn]], ignore_index = True)
            partLimit = tempParaTable.ix[i,"PartLimit"]
            normal = tempParaTable.ix[i,"Normal"]
            shpsegs = []
            for j, conShapePart in enumerate(conShape):
                if j < partLimit:
                    lons, lats = zip(*conShapePart)
                    x, y = m(lons, lats)
                    shpsegs.append(zip(x,y))
                    lines = LineCollection(shpsegs,antialiaseds=(1,))
                    lines.set_facecolors(cm.gray(1 - normal))
                    lines.set_linewidth(0.01)
                    ax.add_collection(lines)
Esempio n. 8
0
def mapcountries(countries):  #Map list of countries?
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt
    fig = plt.figure(figsize=(11.7, 8.3))
    plt.subplots_adjust()
    m = Basemap(projection='hammer', resolution=None, lon_0=0)
    m.drawcountries(linewidth=0.5)
    m.drawcoastlines(linewidth=0.5)

    from shapelib import ShapeFile
    import dbflib
    from matplotlib.collections import LineCollection
    from matplotlib import cm

    #for ctry in countries:
    shp = ShapeFile(r"borders/world_adm1")
    dbf = dbflib.open(r"borders/world_adm1")

    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []
        shp_object = shp.read_obj(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
            if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(
                    lats) < -91.:
                raise ValueError('Lats/Lons out of range')
            x, y = m(lons, lats)
            shpsegs.append(zip(x, y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            name = shapedict["NAME_1"]

            shapedict['RINGNUM'] = ring + 1
            shapedict['SHAPENUM'] = npoly + 1
            shpinfo.append(shapedict)
        print(name)
        lines = LineCollection(shpsegs, antialiaseds=(1, ))
        lines.set_facecolors(cm.jet(0.5))
        lines.set_edgecolors('k')
        lines.set_linewidth(0.3)
        ax.add_collection(lines)

    plt.show()
def algo (region,output, word):
    reg = [0 for i in range(0,23)]
    total = 0
    for line in region: #reg_num number
        items = line.rstrip('\n').split('\t')
        reg[int(items[0])]=int(items[1])
        total = total+int(items[1])
    reg=np.array(reg)
    max_percent=np.max(reg)
    plt.figure(figsize=(15,15))
    ax = plt.subplot(111)
    m = Basemap(projection='merc', lat_0=45, lon_0=0,
                resolution = 'h', area_thresh = 10.0,
                llcrnrlat=41.33, llcrnrlon=-5,   
                urcrnrlat=51.5, urcrnrlon=9.7) 
    m.drawcoastlines()
    #m.drawcountries()  # french border does not fit with region ones
    m.fillcontinents(color='lightgrey',lake_color='white')
    m.drawmapboundary(fill_color='white')

    sf = shapefile.Reader("./geodata/FRA_adm1")
    shapes = sf.shapes()
    records = sf.records()
    for record, shape in zip(records,shapes):
        lons,lats = zip(*shape.points)
        data = np.array(m(lons, lats)).T
        if len(shape.parts) == 1:
            segs = [data,]
        else:
            segs = []
            for i in range(1,len(shape.parts)):
                index = shape.parts[i-1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
            segs.append(data[index2:])
        
        lines = LineCollection(segs,antialiaseds=(1,))
        lines.set_edgecolors('k')
        lines.set_linewidth(0.5)
        lines.set_facecolors('brown')
        lines.set_alpha(float(reg[record[3]])/max_percent) #record[3] est le numero de region
        ax.add_collection(lines)   

    plt.savefig(word+'-'+str(total)+'.png',dpi=300)

    return 0
Esempio n. 10
0
    def plot(self, ax=None, cmapname=None, cmap=None, linewidth=1,
             edgecolor='grey', facecolor=None, alpha=1):
        """Plot the geometries on the basemap using the defined colors

        Parameters:
        -----------
        ax : matplotlib.axis object
            An axis object for plots. Overwrites the self.ax attribute.
        cmapname : string
            Name of the color map from matplotlib (LINK!) (default: 'seismic')
        cmap : matplotlib colormap
            You can create you own colormap and pass it to the plot.
        linewidth : float
            Width of the lines.
        edgecolor : string, float or iterable
            Definition of the edge color. Can be an iterable with a color
            definition for each geometry, a string with one color for
            all geometries or a float to define one color for all geometries
            from the cmap.
        facecolor : string, float or iterable
            Definition of the face color. See edgecolor.
        alpha : float
            Level of transparency.
        """
        if ax is not None:
            self.ax = ax
        n = 0
        if facecolor is None:
            facecolor = self.color
        if edgecolor is None:
            edgecolor = self.color
        if cmapname is not None:
            self.cmapname = cmapname
        if self.data is not None:
            self.data = np.array(self.data)
        if cmap is None:
            cmap = plt.get_cmap(self.cmapname)
        for geo in self.geometries:
            vectors = self.get_vectors_from_postgis_map(geo)
            lines = LineCollection(vectors, antialiaseds=(1, ))
            lines.set_facecolors(self.select_color(facecolor, cmap, n))
            lines.set_edgecolors(self.select_color(edgecolor, cmap, n))
            lines.set_linewidth(linewidth)
            lines.set_alpha(alpha)
            self.ax.add_collection(lines)
            n += 1
Esempio n. 11
0
    def _collect_geoms(self, query_object, ax, m, el_limit=5000):
        """
        Create vectors for different geom and multi-geom types
        :rtype: subplot
        :param query_object:
        :param ax: Instance of plot.subplot()
        :param m: Instance of Basemap()
        :param el_limit: Maximum number of elements to display on map
        :return: subplot instance
        """
        # Collect fetched geometries
        if not len(query_object.results) > el_limit:
            try:
                for el in query_object.results:
                    vectors = query_object._get_vectors_from_postgis_map(m,
                                                                         loads(
                                                                             el[
                                                                                 'geom']))
                    lines = LineCollection(vectors, antialiaseds=(1,))
                    if not query_object.geom_type == 'LineString':
                        lines.set_facecolors('red')
                    lines.set_linewidth(0.25)
                    ax.add_collection(lines)
            # If AttributeError assume geom_type 'Point', simply collect all
            # points and perform scatterplot
            except AttributeError:
                xy = m(
                    [loads(point['geom']).x for point in query_object.results],
                    [loads(point['geom']).y for point in query_object.results])
                ax.scatter(xy[0], xy[1])

                # # Add clipping border
                # if self.region.boundary_polygon:
                #     vectors = self.__get_vectors_from_postgis_map(m, loads(
                #         self.region.boundary_polygon))
                #     border = LineCollection(vectors, antialiaseds=(1,))
                #     border.set_edgecolors('black')
                #     border.set_linewidth(1)
                #     border.set_linestyle('dashed')
                #     ax.add_collection(border)

        else:
            logger.printmessage.error("Error: >5000 elements to plot!")

        return ax
Esempio n. 12
0
def drawShape(m, ax, paraTable):
    for conshpfn in paraTable["ShapeFile"].unique():
        for i, conShape in enumerate(getPointArray(conshpfn)):
            tempParaTable = concat(
                [paraTable[paraTable["ShapeFile"] == conshpfn]],
                ignore_index=True)
            partLimit = tempParaTable.ix[i, "PartLimit"]
            normal = tempParaTable.ix[i, "Normal"]
            shpsegs = []
            for j, conShapePart in enumerate(conShape):
                if j < partLimit:
                    lons, lats = zip(*conShapePart)
                    x, y = m(lons, lats)
                    shpsegs.append(zip(x, y))
                    lines = LineCollection(shpsegs, antialiaseds=(1, ))
                    lines.set_facecolors(cm.gray(1 - normal))
                    lines.set_linewidth(0.01)
                    ax.add_collection(lines)
def plotCountry(m, ax, id, path='gadm0'):
    country, lonlat = merged[id]

    r = shapefile.Reader(r"%s/%s_adm0" % (path, country))
    shapes = r.shapes()
    records = r.records()

    for record, shape in zip(records, shapes):
        lons, lats = zip(*shape.points)
        data = np.array(m(lons, lats)).T

        if len(shape.parts) == 1:
            segs = [
                data,
            ]
        else:
            segs = []
            for i in range(1, len(shape.parts)):
                index = shape.parts[i - 1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
            segs.append(data[index2:])

        lines = LineCollection(segs, antialiaseds=(1, ))
        lines.set_facecolors('lightgreen')
        lines.set_edgecolors('k')
        lines.set_linewidth(0.1)
        lines.set_alpha(0.5)
        ax.add_collection(lines)

    # Add country centroid
    lon, lat = lonlat
    xpt, ypt = m(lon, lat)
    txt = ax.annotate(id, (xpt, ypt),
                      color='r',
                      size='medium',
                      ha='center',
                      va='center',
                      path_effects=[
                          PathEffects.withStroke(linewidth=3, foreground="w"),
                          PathEffects.withSimplePatchShadow()
                      ])
Esempio n. 14
0
 def drawcountry(self,
                 ax,
                 base_map,
                 iso2,
                 color,
                 alpha = 1):
     if iso2 not in self.countries:
         raise ValueError, "Where is that country ?"
     vertices = self.countries[iso2]
     shape = []
     for vertex in vertices:
         longs, lats = zip(*vertex)
         # conversion to plot coordinates
         x,y = base_map(longs, lats)
         shape.append(zip(x,y))
     lines = LineCollection(shape,antialiaseds=(1,))
     lines.set_facecolors(cm.hot(np.array([color,])))
     lines.set_edgecolors('white')
     lines.set_linewidth(0.5)
     lines.set_alpha(alpha)
     ax.add_collection(lines)
Esempio n. 15
0
def polyPlotShapeFile(m, ax, sf, crs):
    import numpy as np
    import pyproj
    from matplotlib.collections import LineCollection
    from matplotlib import cm
    import matplotlib.pyplot as plt

    shapes = sf.shapes()
    records = sf.records()

    shp_proj = pyproj.Proj(crs.to_proj4())  #.shp file projection
    std_proj = pyproj.Proj(init='epsg:4326')  # Lat/Lon system

    for record, shape in zip(records, shapes):
        lons, lats = zip(*shape.points)
        lons, lats = pyproj.transform(shp_proj, std_proj, lons, lats)
        data = np.array(m(lons, lats)).T

        if record['POLY_TYPE'] == 'I':
            if len(shape.parts) == 1:
                segs = [
                    data,
                ]
            else:
                segs = []
                for i in range(1, len(shape.parts)):
                    index = shape.parts[i - 1]
                    index2 = shape.parts[i]
                    segs.append(data[index:index2])
                segs.append(data[index2:])

            lines = LineCollection(segs,
                                   antialiaseds=(1, ),
                                   zorder=1,
                                   alpha=0.2)
            lines.set_facecolors('b')
            # lines.set_facecolors(cm.jet(np.random.rand(1)))
            lines.set_edgecolors('k')
            lines.set_linewidth(1)
            ax.add_collection(lines)
Esempio n. 16
0
def plotclustering(label, zipcodes, nameee):
#    print len(zipcodes)
    label = np.array(label)
    zipcodes = np.array(zipcodes)
    cluster1 = zipcodes[label == 1]
    cluster2 = zipcodes[label == 2]
    cluster0 = zipcodes[label == 0]
    cluster3 = zipcodes[label == 3]

    fig = plt.figure(figsize =(15, 15))
    ax = plt.subplot(111)
    lllat = 40.473; urlat = 40.93; lllon = -74.27; urlon = -73.69 # define the boundary of the map
    m = Basemap(ax=ax, projection = 'stere', lon_0 = (urlon + lllon)/2, lat_0 = (urlat +lllat)/2, llcrnrlon = lllon, llcrnrlat = lllat, urcrnrlon = urlon, urcrnrlat = urlat, resolution= 'l')# create the basemap 

  #  m.drawcoastlines()
    m.drawcountries()
    shp = ShapeFile('c:/Users/gang/Desktop/nyczipregion')
    dbf = dbflib.open('c:/Users/gang/Desktop/nyczipregion')
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons , lats = zip(*verts[ring])
            x, y = m(lons, lats)
            shpsegs.append(zip(x, y))
            if ring ==0:
                shapedict = dbf.read_record(npoly)
            name = shapedict['Zcta5ce00']
        
        lines = LineCollection(shpsegs, antialiaseds=(1,))
        if name in cluster0:
            lines.set_facecolors('b')
        if name in cluster1:
            lines.set_facecolors('g')
        if name in cluster2:
            lines.set_facecolors('r')
        if name in cluster3:
            lines.set_facecolors('y')
        lines.set_alpha(1)
        lines.set_edgecolors('k')
        ax.add_collection(lines)
    plt.title('Box Clustering Based On Taxi Trips')
    plt.savefig(nameee+'_box_trip_Clustering.png', dpi=300)
    plt.show()   
Esempio n. 17
0
def generate_map(countries):

    # Initialize plotting area, set the boundaries and add a sub-plot on which
    # we are going to plot the map
    fig = plt.figure(figsize=(11.7, 8.3))
    plt.subplots_adjust(left=0.05,
                        right=0.95,
                        top=0.90,
                        bottom=0.05,
                        wspace=0.15,
                        hspace=0.05)
    ax = plt.subplot(111)

    # Initialize the basemap, set the resolution, projection type and the viewport
    bm = Basemap(resolution='i', projection='robin', lon_0=0)

    # Tell basemap how to draw the countries (built-in shapes), draw parallels and meridians
    # and color in the water
    bm.drawcountries(linewidth=0.5)
    bm.drawparallels(np.arange(-90., 120., 30.))
    bm.drawmeridians(np.arange(0., 360., 60.))
    bm.drawmapboundary(fill_color='aqua')

    # Open the countries shapefile and read the shape and attribute information
    r = shapefile.Reader('world_borders/TM_WORLD_BORDERS-0.3.shp')
    shapes = r.shapes()
    records = r.records()

    # Iterate through all records (attributes) and shapes (countries)
    for record, shape in zip(records, shapes):

        # Extract longitude and latitude values into two separate arrays then
        # project the coordinates onto the map projection and transpose the array, so that
        # the data variable contains (lon, lat) pairs in the list.
        # Basically, the following two lines convert the initial data
        #  [ [lon_original_1, lat_original_1], [lon_original_2, lat_original_2], ... ]
        # into projected data
        #  [ [lon_projected_1, lat_projected_1, [lon_projected_2, lat_projected_2], ... ]
        #
        # Note: Calling baseshape object with the coordinates as an argument returns the
        #       projection of those coordinates
        lon_array, lat_array = zip(*shape.points)
        data = np.array(bm(lon_array, lat_array)).T

        # Next we will create groups of points by splitting the shape.points according to
        # the indices provided in shape.parts

        if len(shape.parts) == 1:
            # If the shape has only one part, then we have only one group. Easy.
            groups = [
                data,
            ]
        else:
            # If we have more than one part ...
            groups = []
            for i in range(1, len(shape.parts)):
                # We iterate through all parts, and find their start and end positions
                index_start = shape.parts[i - 1]
                index_end = shape.parts[i]
                # Then we copy all point between two indices into their own group and append
                # that group to the list
                groups.append(data[index_start:index_end])
            # Last group starts at the last index and finishes at the end of the points list
            groups.append(data[index_end:])

        # Create a collection of lines provided the group of points. Each group represents a line.
        lines = LineCollection(groups, antialiaseds=(1, ))
        # We then select a color from a color map (in this instance all Reds)
        # The intensity of the selected color is proportional to the number of requests.
        # Color map accepts values from 0 to 1, therefore we need to normalize our request count
        # figures, so that the max number of requests is 1, and the rest is proportionally spread
        # in the range from 0 to 1.
        max_value = float(max(countries.values()))
        country_name = record[4]

        requests = countries.get(country_name, 0)
        requests_norm = requests / max_value

        lines.set_facecolors(cm.Reds(requests_norm))

        # Finally we set the border color to be black and add the shape to the sub-plot
        lines.set_edgecolors('k')
        lines.set_linewidth(0.1)
        ax.add_collection(lines)

    # Once we are ready, we save the resulting picture
    plt.savefig('requests_per_country.png', dpi=300)
Esempio n. 18
0
	            index = shape.parts[i-1]
	            index2 = shape.parts[i]
	            segs.append(data[index:index2])
	        segs.append(data[index2:])
	 
	    lines = LineCollection(segs,antialiaseds=(1,))
	    #Now obtain the data in a given poly and assign a color to the value
	    div = str(record[5])
	    dval = divlookup(dfile,div,yyyy,int(mm))
	    if(len(div) < 4): div = '0'+div
	    nval = normlookup(normfile, div, int(mm))
	    dval = dval-nval
	    #Now normalize the data and map it to the color ramp
	    dval = (dval - valmin) * (255/(valmax-valmin))
	    #if(dval > valmax): dval = valmax - 0.1
	    lines.set_facecolors(cmap(int(dval)))
	    lines.set_edgecolors(cmap(int(dval)))
	    lines.set_linewidth(0.25)
	    ax1.add_collection(lines)

if(imgsize == 'GEO'):
	inProj = Proj(init='epsg:3338')
	outProj = Proj(init='epsg:4326')
	#Now read in the Alaska Climate Division Shapes and fill the basemap 
	s = shapefile.Reader(r"./Shapefiles/AK_divisions_NAD83")
	shapes = s.shapes()
	records = s.records()
	

	for record, shape in zip(records,shapes):
	    lons,lats = zip(*shape.points)
def drawMap(filename,names,totalCount):
  countries = json.loads(open(filename).read())["features"]

  for country in countries:
    name = country["properties"]["name"]
    polygonList = country["geometry"]["coordinates"]
    polygonType = country["geometry"]["type"]
    shpsegs = []

    print "Processing %s [%d/%s] ..." % (unicode(name).encode("utf-8"), len(polygonList), polygonType)
    maxverts = 0
    maxindex = 0
    counter = 0
    for polygon in polygonList:
      if polygonType == "MultiPolygon":
        for p in polygon:
          if len(p) == 1:
            p = p[0]
          if p[0] != p[-1]:
            p.append(p[0])

          lons, lats = zip(*p)
          x, y = m(lons, lats)
          shpsegs.append(zip(x,y))
          if len(x) > maxverts:
            maxverts = len(x)
            maxindex = counter
          counter+=1
      else:
        if len(polygon) == 1:
          polygon = polygon[0]
        if polygon[0] != polygon[-1]:
          polygon.append(polygon[0])

        lons, lats = zip(*polygon)
        x, y = m(lons, lats)
        shpsegs.append(zip(x,y))
        if len(x) > maxverts:
          maxverts = len(x)
          maxindex = counter
        counter+=1

    # Compute centroid
    centroid = Polygon(shpsegs[maxindex]).centroid

    # Create country shape
    lines = LineCollection(shpsegs,antialiaseds=(1,))
    lines.set_edgecolors('k')
    lines.set_linewidth(0.5)

    #import brewer2mpl
    #colormap = brewer2mpl.get_map('Paired', 'qualitative', 12).mpl_colors
    colormap = [(0.6509803921568628, 0.807843137254902, 0.8901960784313725), (0.12156862745098039, 0.47058823529411764, 0.7058823529411765), (0.6980392156862745, 0.8745098039215686, 0.5411764705882353), (0.2, 0.6274509803921569, 0.17254901960784313), (0.984313725490196, 0.6039215686274509, 0.6), (0.8901960784313725, 0.10196078431372549, 0.10980392156862745), (0.9921568627450981, 0.7490196078431373, 0.43529411764705883), (1.0, 0.4980392156862745, 0.0), (0.792156862745098, 0.6980392156862745, 0.8392156862745098), (0.41568627450980394, 0.23921568627450981, 0.6039215686274509), (1.0, 1.0, 0.6), (0.6941176470588235, 0.34901960784313724, 0.1568627450980392)]

    # Add color and label if covered by Safecast
    if name in names.keys():
      color = colormap[(int((float(names[name][0])/totalCount)*12)+1)]
      lines.set_label("%s - %0.1fK (%d)" % (name, names[name][0]/1000.0, names[name][1]) )
      #lines.set_label(name)
      lines.set_edgecolors(color)
      lines.set_facecolors(color)
      label = plt.text(centroid.x, centroid.y, "%d" % names[name][1], fontsize=5, ha='center', va='center', color='k', fontweight='bold')
      plt.setp(label, path_effects=[PathEffects.withStroke(linewidth=2, foreground="w")])
    ax.add_collection(lines)
Esempio n. 20
0
    def choropleth(self, adm_num_dicts, level = 'department', source='gadm', cmap_base=plt.cm.YlOrRd, ret_colormap_and_label=True, bin_lims=None, nbins=5, linewidth=0.4):
        """
        A choropleth map by department  or municipality. The dataset for boundaries of administrative areas is taken from GADM database 
        Original code is from here: https://github.com/astivim/Nicaragua-Population-Density-Map    
        
        Input:
        - adm_num_dicts: a list of dictionaries with the following key-value pairs: {'adm' : str, 'num' : float}
        - bin_lims (optional): values of bin edges
        - nbins (optional): number of bins, default = 5. Ignored if bin_lims is specified. 
        - cmap_base: base colormap. Default is plt.cm.YlOrRd (red)  
        - ret_colormap_and_label=True. If True, return colormap_label = {'bin_labels' : bin_labels, 'colormap' : custom_cmap} used for plotting. If False, colormap_label = None  

        Return: colormap_label = {'bin_labels' : bin_labels, 'colormap' : custom_cmap}
        """	
        # Divide nums into bins. For each entry in nums, assign to which bin it belongs to, then assign a color to each bin.
        
        adms = [item['adm'] for item in adm_num_dicts]
        nums  = [item['num'] for item in adm_num_dicts]  
        
        # Define bin_lims by dividing the range of nums into equally spaced portions
        if bin_lims:
            nbins = len(bin_lims)                
        else:
            temp_nums = [num for num in nums if num]
            bin_spacing = (max(temp_nums) - min(temp_nums) + 1) / nbins                
            bin_lims = np.arange(min(temp_nums), max(temp_nums) + bin_spacing, bin_spacing)
            nbins = len(bin_lims) 
            
        # Assign each num in nums into its respective bin and assign color. Use only nbins values from the colormap (cmap)
        nums_bin_ix = np.digitize(nums, bin_lims)      
        nums_bin_ix = [idx if idx < nbins else 0 for idx in nums_bin_ix]    
        cmaplist = [cmap_base(i) for i in range(cmap_base.N)]
        del_colors = np.int(np.ceil(cmap_base.N/float(nbins-1)))
        map_colors = cmaplist[0::del_colors]
        map_colors.insert(0, (1.0, 1.0, 1.0, 1.0))             # fill with white if no data (num is None)
        
        # Load the geographical data (shapefile and record)
        if level == 'department':
            fpath = os.path.join(self.data_dir, "NIC_adm/NIC_adm1")
        elif level == 'municipality':
            fpath = os.path.join(self.data_dir, "NIC_adm/NIC_adm2")
        else:
            print("Level unrecognized. Use 'department'")
            fpath = os.path.join(self.data_dir, "NIC_adm/NIC_adm1")
            
        r = shapefile.Reader(fpath)
        shapes = r.shapes()
        records = r.records()
        
        # Extract lat and lon data from the GADM shapefile and assign a facecolor to each department 
        for record, shape in zip(records, shapes):
            lons, lats = zip(*shape.points)
            data = [(lon, lat) for lon, lat in zip(*self(lons, lats))]
            if level == 'department':
                adm_name = record[4]
            else:
                adm_name = record[6]
            
            try:
                adm_idx = adms.index(adm_name)
                adm_num = adm_num_dicts[adm_idx]['num']
                color_idx = nums_bin_ix[adm_idx] 
            except ValueError:
                adm_num = None
                color_idx = 0

            if len(shape.parts) == 1:
                segs = [data, ]
            else:
                segs = []
                for i in range(1,len(shape.parts)):
                    index = shape.parts[i-1]
                    index2 = shape.parts[i]
                    segs.append(data[index:index2])
                
                segs.append(data[index2:])
            lines = LineCollection(segs, antialiaseds=(1,))            
            
            color = map_colors[color_idx] if adm_name not in ["Lago Nicaragua", "Lago de Nicaragua"] else 'aqua'
            lines.set_facecolors(color)
            lines.set_linewidth(linewidth)
            self.ax.add_collection(lines)
        
        if ret_colormap_and_label:
            custom_cmap = mpl.colors.ListedColormap(map_colors[1: ], name='from_list')
            bins = [(i1,i2) for i1,i2 in zip(bin_lims[0:nbins], bin_lims[1:nbins+1])]
            bin_labels = ["(%d - %d)" % (b[0],b[1]) for b in bins]
            colormap_label = {'bin_labels' : bin_labels, 'colormap' : custom_cmap}
        else:
            colormap_label = None
        
        return colormap_label
shapes = shpf.shapes()
records = shpf.records()
 
# show only CA and AK (for example)
for record, shape in zip_filter_by_state(records, shapes, ['06', '02']):
    lons,lats = zip(*shape.points)
    data = np.array(m(lons, lats)).T
 
    if len(shape.parts) == 1:
        segs = [data,]
    else:
        segs = []
        for i in range(1,len(shape.parts)):
            index = shape.parts[i-1]
            index2 = shape.parts[i]
            segs.append(data[index:index2])
        segs.append(data[index2:])
 
    lines = LineCollection(segs,antialiaseds=(1,))
    lines.set_facecolors(cm.jet(np.random.rand(1)))
    lines.set_edgecolors('k')
    lines.set_linewidth(0.1)
    ax.add_collection(lines)
 
plt.savefig('tutorial10.png',dpi=300)
plt.show()

# <codecell>


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

    else:
        color = "#666666"

    some_points = feature["geometry"]["coordinates"]
    lons, lats = np.array(some_points).T
    data = np.array(m(lons, lats)).T

    lines = LineCollection(data)

    lines.set_edgecolors("#333333")
    lines.set_facecolors(color)
    lines.set_linewidth(0.3)
    ax.add_collection(lines)
    
ax1 = fig.add_axes([0.83, 0.05, 0.03, 0.92])
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
cbar = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, orientation="vertical")
cbar.set_label("Avg. Gross Co-op Rental Income per Sq. Ft ($)")
dv = 5.
cbar.set_ticks(np.arange(vmin, vmax+dv, dv))
cbar.ax.minorticks_on()
plt.savefig("coop_rental_map.png")
plt.show()
Esempio n. 23
0
        if ring == 0:
            shapedict = dbf.read_record(npoly)
        #print shapedict
        name = shapedict["ID_DEPART"]
        subpref_id = shapedict["ID_SP"]
        # add information about ring number to dictionary.
        shapedict['RINGNUM'] = ring+1
        shapedict['SHAPENUM'] = npoly+1
        shpinfo.append(shapedict)
    lines = LineCollection(shpsegs,antialiaseds=(1,))
    if subpref_id <> 60:
        colorVal = scalarMap.to_rgba(values[region_pole[subpref_region[subpref_id]]])
    else:
        colorVal = 'y'
    print name, subpref_id, colorVal
    lines.set_facecolors(colorVal)
    lines.set_edgecolors('gray')
    lines.set_linewidth(0.1)
    ax.add_collection(lines)  

# data to plot on the map    
lons = []
lats = []
num = []

# if wanna plot subpref ids only
for subpref in range(1,256):
    lons.append(subpref_coord[subpref][0])
    lats.append(subpref_coord[subpref][1])
    num.append(subpref)    
Esempio n. 24
0
def make_country_map(countrylist,
                     shapefilename,
                     m,
                     figname,
                     year=None,
                     bounds=(1, 2, 4, 6, 8, 10, 15, 20),
                     cmap=cm.YlGnBu,
                     logofile="../logos/logo_colloquium.png"):
    """
    :param countrylist: list of country iso-codes
    :type countrylist: list
    :param shapefilename: path of the shape file
    :type shapefilename: str
    :param m: projection created with Basemap
    :param figname: path of the figure to be created
    :type figname: str
    :param year: considered year
    :type year: int
    :param bounds: bounds of the colorbar
    :param cmap: colormap
    :param logofile: file storing the CLQ logo
    :type logofile: str
    :return:
    """

    # Count the occurrence of each country in the list
    countrycount = Counter(countrylist)
    nmax = max(countrycount.values())

    shapes, records = read_shape(shapefilename)

    fig = plt.figure(figsize=(11.7, 8.3))
    ax = plt.subplot(111)
    rcParams.update({'font.size': 16})

    if year is not None:
        titletext = "{0}: {1} participants".format(year, len(countrylist))
        plt.title(titletext, fontsize=20)

    m.drawcountries(linewidth=0.1)
    m.drawcoastlines(linewidth=0.1)
    """
    axins = zoomed_inset_axes(ax, 2.5, loc=3)
    m.drawcountries(linewidth=.2, ax=axins)
    x, y = m(-15., 35.)
    x2, y2 = m(27, 60.)
    axins.set_xlim(x, x2)
    axins.set_ylim(y, y2)
    axins.axis('off')
    """

    for record, shape in zip(records, shapes):
        countryname = record[1]
        if countryname in countrycount:
            lons, lats = zip(*shape.points)
            data = np.array(m(lons, lats)).T

            if len(shape.parts) == 1:
                segs = [
                    data,
                ]
            else:
                segs = []
                for i in range(1, len(shape.parts)):
                    index = shape.parts[i - 1]
                    index2 = shape.parts[i]
                    segs.append(data[index:index2])
                segs.append(data[index2:])

            lines = LineCollection(segs, antialiaseds=(1, ))
            lines.set_facecolors(cmap(countrycount[countryname] / nmax))
            lines.set_edgecolors('k')
            lines.set_linewidth(0.1)
            ax.add_collection(lines)
            """
            lines2 = LineCollection(segs, antialiaseds=(1,))
            lines2.set_facecolors(cmap(countrycount[countryname] / nmax))
            lines2.set_edgecolors('k')
            lines2.set_linewidth(0.1)
            axins.add_collection(lines2)
            """

    cax = fig.add_axes([0.475, 0.21, 0.4, 0.02])
    cmap.set_over((0., 0., 0.))
    cb1 = colorbar.ColorbarBase(cax,
                                cmap=cmap,
                                norm=colors.BoundaryNorm(bounds, cmap.N),
                                orientation='horizontal',
                                spacing='uniform',
                                extend='max',
                                label='Number of participants')

    cb1.ax.xaxis.set_label_position('top')

    if os.path.exists(logofile):
        im = plt.imread(logofile)
        newax = fig.add_axes([0.85, 0.85, 0.07, 0.07], anchor='NE')
        newax.imshow(im)
        newax.axis('off')

    # Remove frame
    ax.axis('off')
    # Add year in upper-left corner
    # plt.annotate(year, xy=(0.05, 8.5), xycoords='axes fraction', fontsize=30)

    plt.savefig(figname, dpi=300, bbox_inches='tight')
    # plt.show()
    plt.close()
def map_wake_hr(thersholdX):

    mpl.rcParams['font.size'] = 4.4
    
    ###########################################################################################
    fig = plt.figure(3)
    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
    ax = plt.subplot(111)
    
    m = Basemap(llcrnrlon=-9, \
                    llcrnrlat=3.8, \
                    urcrnrlon=-1.5, \
                    urcrnrlat = 11, \
                    resolution = 'h', \
                    projection = 'tmerc', \
                    lat_0 = 7.38, \
                    lon_0 = -5.30)
        
    subpref_wake_hr = read_in_subpref_wake_hr(thersholdX)
    # read the shapefile archive
    s = m.readshapefile('/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE', 'subpref')
    
    max7s = 1
    min7s = 10000000
    for subpref in subpref_wake_hr.keys():
        if subpref_wake_hr[subpref] > max7s:
            max7s = subpref_wake_hr[subpref]
        if subpref_wake_hr[subpref] < min7s:
            min7s = subpref_wake_hr[subpref]
            
    max7s = float(max7s)
    print "max", (max7s)
    print "min", (min7s)
    
#     scaled_weight = defaultdict(int)
#     for i in range(256):
#         scaled_weight[i] = defaultdict(int)
#     for subpref in subpref_wake_hr.keys():
#         scaled_weight[subpref] = (subpref_wake_hr[subpref] - min7s) / (max7s - min7s)
    
#     values = range(256)    
#     jet = cm = plt.get_cmap('jet') 
#     cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
#     scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

    # define custom colormap, white -> nicered, #E6072A = RGB(0.9,0.03,0.16)
    cdict = {'red':  ( (0.0,  1.0,  1.0),
                       (1.0,  0.9,  1.0) ),
             'green':( (0.0,  1.0,  1.0),
                       (1.0,  0.03, 0.0) ),
             'blue': ( (0.0,  1.0,  1.0),
                       (1.0,  0.16, 0.0) ) }
    custom_map = LinearSegmentedColormap('custom_map', cdict, N=33)
    plt.register_cmap(cmap=custom_map)

        
    subpref_coord = read_in_subpref_lonlat()
    
    shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []
           
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
    #        if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
    #            raise ValueError,msg
            x, y = m(lons, lats)
            shpsegs.append(zip(x,y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            #print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            print name, subpref_id
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring+1
            shapedict['SHAPENUM'] = npoly+1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs,antialiaseds=(1,))
        colorVal = custom_map(subpref_wake_hr[subpref_id])
#         colorVal = scaled_weight[subpef]
        lines.set_facecolors(colorVal)
        lines.set_edgecolors('gray')
        lines.set_linewidth(0.1)
        ax.add_collection(lines)  
    
    # data to plot on the map    
    lons = []
    lats = []
    num = []

        
    for subpref in subpref_wake_hr.iterkeys():
        print(subpref)
        if subpref <> 0 and subpref <> -1:
            lons.append(subpref_coord[subpref][0])
            lats.append(subpref_coord[subpref][1])
            num.append(subpref_wake_hr[subpref])
        
    x, y = m(lons, lats)
    m.scatter(x, y, color='white')
    
    for name, xc, yc in zip(num, x, y):
        # draw the pref name in a yellow (shaded) box
            plt.text(xc, yc, name)
            

    
    plt.savefig("/home/sscepano/Project7s/D4D/CI/call_wakeup_sleep_hour/subpref_wake_" + str(thersholdX) + "pct.png",dpi=350)
Esempio n. 26
0
def map_communities_and_commutes(G):
    import networkx as nx
    
    G_mod = nx.read_gml("/home/sscepano/D4D res/allstuff/User movements graphs/commuting patterns/1/total_commuting_G_10com_775_269_v2.gml")
    col = [str]*256
    
    for i in range(256):
        col[i] = 'w'
    
    for node in G_mod.nodes_iter(data=True):
        #print node[1]['label']
        col_gephi = node[1]['graphics']['fill']
        while (len(col_gephi) < 7):
            col_gephi += '0'
        col[int(float(node[1]['label']))] = col_gephi
        
        
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    
    import matplotlib as mpl
    mpl.rcParams['font.size'] = 10.
    mpl.rcParams['axes.labelsize'] = 8.
    mpl.rcParams['xtick.labelsize'] = 6.
    mpl.rcParams['ytick.labelsize'] = 6.
    
    from shapelib import ShapeFile
    import dbflib
    from matplotlib.collections import LineCollection
    from matplotlib import cm
    
    
    ###########################################################################################
    
    fig = plt.figure(3)
    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
    ax = plt.subplot(111)
    
    m = Basemap(llcrnrlon=-9, \
                    llcrnrlat=3.8, \
                    urcrnrlon=-1.5, \
                    urcrnrlat = 11, \
                    resolution = 'h', \
                    projection = 'tmerc', \
                    lat_0 = 7.38, \
                    lon_0 = -5.30)
    
    m.drawcoastlines()
    
    
    shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []
        
        
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
    #        if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
    #            raise ValueError,msg
            x, y = m(lons, lats)
            shpsegs.append(zip(x,y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            #print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            #color_col
            
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring+1
            shapedict['SHAPENUM'] = npoly+1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs,antialiaseds=(1,))
        lines.set_facecolors(col[subpref_id])
        lines.set_edgecolors('k')
        lines.set_linewidth(0.3)
        ax.add_collection(lines)
        
    
    from collections import defaultdict    
        
    if G.has_node(-1): 
        G.remove_node(-1)
    
    max7s = 1
    min7s = 1
    for u,v,d in G.edges(data=True):
        if d['weight'] > max7s:
            max7s = d['weight']
        if d['weight'] < min7s:
            min7s = d['weight']
            
    max7s = float(max7s)
    print max7s
    print min7s
    
    scaled_weight = defaultdict(int)
    for i in range(256):
        scaled_weight[i] = defaultdict(int)
    
    for u,v,d in G.edges(data=True):
        scaled_weight[u][v] = (d['weight'] - min7s) / (max7s - min7s)
    
    for u, v, d in G.edges(data=True):
        lo = []
        la = []   
        lo.append(lons[u])
        lo.append(lons[v])
        la.append(lats[u])
        la.append(lats[v])
        x, y = m(lo, la)
        linewidth7s = scaled_weight[u][v] * 6.5 + 0.15
        m.plot(x,y, linewidth= linewidth7s)
        if linewidth7s > 1:
            print linewidth7s
        
    plt.savefig('/home/sscepano/D4D res/allstuff/User movements graphs/commuting patterns/1/maps/mod_classes_10com_775_269_v2.png',dpi=1000)
    #plt.show()
    
    ###################################################################################################3
    
    return
Esempio n. 27
0
    rings = len(verts)
    for ring in range(rings):
        lons, lats = zip(*verts[ring])
        x, y = m(lons, lats)
        shpsegs.append(zip(x,y))
        if ring == 0:
            shapedict = dbf.read_record(npoly)
        print shapedict
        name = shapedict["ID_DEPART"]
        subpref_id = shapedict["ID_SP"]
        num = ["%.2f" % rg[subpref_id]]
#        for name, xc, yc in zip(num, x, y):
#            plt.text(xc, yc, name)
        #color_col
        
        # add information about ring number to dictionary.
        shapedict['RINGNUM'] = ring+1
        shapedict['SHAPENUM'] = npoly+1
        shpinfo.append(shapedict)
    #print subpref_id
    #print name
    lines = LineCollection(shpsegs,antialiaseds=(1,))
    lines.set_facecolors(str(1 - rg[subpref_id]))
    lines.set_edgecolors('k')
    lines.set_linewidth(0.3)
    ax.add_collection(lines)

    
plt.savefig('/home/sscepano/D4D res/allstuff/rg/grayscale_rg_map.png',dpi=1000)
#plt.show()
Esempio n. 28
0
def country(countries, bmap, fc=None, ec='none', lw=1, alpha=1, adm=0, gadmpath='/home/dtr/Documents/Webpages/blog-notebooks/data/TravelMap/'):
    """Colour <countries> with a <bmap> projection.
    
    This script is adapted from:
    http://www.geophysique.be/2013/02/12/
                           matplotlib-basemap-tutorial-10-shapefiles-unleached-continued
                           
    I downloaded the countries shapefile from the *Global Administrative Areas*
    website, [gadm.org](http://gadm.org).
    => You have to use the same abbreviations for the countries as GADM does, or adjust the script.
    => You have to download the shapefiles from GADM, and extract them into the <gadmpath> directory.

    Of course, you can use any other shapfiles you have, and adjust the script accordingly.

    Parameters
    ----------
    countries : string or list of strings
        Countries to be plotted.
    bmap : handle
        As you get from bmap = Basemap().
    fc : None or colour, or list of colours; <None>
        Face-colour for country; if <None>, it will cycle through colour-cycle.
    ec : 'none' or colour (scalar or list); <'none'>
        Edge-colour for country.
    lw : scalar or list; <1>
        Linewidth for country.
    alpha: scalar or list; <1>
        Transparency.
    adm : {0, 1, 2, 3}; <0>
        Administrative area to choose.
    gadmpath : 'string'
        Absolut or relative path to shapefiles.
    """

    # Ensure countries is a list
    if not isinstance(countries, list):
        countries = [countries,]
        
    # Get current axis
    cax = plt.gca()

    # Loop through the countries
    for country in countries:
    
        # Get shapefile for the country; extract shapes and records
        r = shapefile.Reader(gadmpath+country+'_adm/'+country+'_adm'+str(adm))
        shapes = r.shapes()
        records = r.records()

        # Loop through the records; for adm0 this is only 1 run
        n = 0
        for record, shape in zip(records,shapes):
            lons,lats = zip(*shape.points)
            data = np.array(bmap(lons, lats)).T

            if len(shape.parts) == 1:
                segs = [data,]
            else:
                segs = []
                for i in range(1,len(shape.parts)):
                    index = shape.parts[i-1]
                    index2 = shape.parts[i]
                    segs.append(data[index:index2])
                segs.append(data[index2:])
            lines = LineCollection(segs,antialiaseds=(1,))
            
            # If facecolor is provided, use; else cycle through colours
            if fc:
                if not isinstance(fc, list):
                    lines.set_facecolors(fc)
                else:
                    lines.set_facecolors(fc[n])
            else:
                cycle = cax._get_lines.prop_cycler
                lines.set_facecolors(next(cycle)['color'])

            # Edge colour
            if not isinstance(ec, list):
                lines.set_edgecolors(ec)
            else:
                lines.set_edgecolors(ec[n])
            # Alpha
            if not isinstance(alpha, list):
                lines.set_alpha(alpha)
            else:
                lines.set_alpha(alpha[n])
            # Line width
            if not isinstance(lw, list):
                lines.set_linewidth(lw)
            else:
                lines.set_linewidth(lw[n])


            # Add to current plot
            cax.add_collection(lines)
            n += 1
Esempio n. 29
0
def map_num_users():

    mpl.rcParams['font.size'] = 4.4

    ###########################################################################################
    fig = plt.figure(3)
    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,
                        right=0.95,
                        top=0.90,
                        bottom=0.05,
                        wspace=0.15,
                        hspace=0.05)
    ax = plt.subplot(111)

    m = Basemap(llcrnrlon=-9, \
                    llcrnrlat=3.8, \
                    urcrnrlon=-1.5, \
                    urcrnrlat = 11, \
                    resolution = 'h', \
                    projection = 'tmerc', \
                    lat_0 = 7.38, \
                    lon_0 = -5.30)

    subpref_users = read_in_subpref_num_users()
    # read the shapefile archive
    s = m.readshapefile(
        '/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE',
        'subpref')

    max7s = 1
    min7s = 10000000
    for subpref in subpref_users.keys():
        if subpref_users[subpref] > max7s:
            max7s = subpref_users[subpref]
        if subpref_users[subpref] < min7s:
            min7s = subpref_users[subpref]

    max7s = float(max7s)
    print "max", (max7s)
    print "min", (min7s)

    scaled_weight = defaultdict(int)
    for i in range(256):
        scaled_weight[i] = defaultdict(int)
    for subpref in subpref_users.keys():
        scaled_weight[subpref] = (subpref_users[subpref] - min7s) / (max7s -
                                                                     min7s)

#     values = range(256)
#     jet = cm = plt.get_cmap('jet')
#     cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
#     scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

# define custom colormap, white -> nicered, #E6072A = RGB(0.9,0.03,0.16)
    cdict = {
        'red': ((0.0, 1.0, 1.0), (1.0, 0.9, 1.0)),
        'green': ((0.0, 1.0, 1.0), (1.0, 0.03, 0.0)),
        'blue': ((0.0, 1.0, 1.0), (1.0, 0.16, 0.0))
    }
    custom_map = LinearSegmentedColormap('custom_map', cdict, N=10000)
    plt.register_cmap(cmap=custom_map)

    subpref_coord = read_in_subpref_lonlat()

    shp = ShapeFile(
        r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(
        r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')

    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []

        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        #print shp_object

        for ring in range(rings):
            print ring
            lons, lats = zip(*verts[ring])
            #        if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
            #            raise ValueError,msg
            x, y = m(lons, lats)
            shpsegs.append(zip(x, y))

            if ring == 0:
                shapedict = dbf.read_record(npoly)
            print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            #             print name, subpref_id
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring + 1
            shapedict['SHAPENUM'] = npoly + 1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs, antialiaseds=(1, ))
        colorVal = custom_map(subpref_users[subpref_id])
        #         colorVal = scaled_weight[subpef]
        lines.set_facecolors(colorVal)
        lines.set_edgecolors('gray')
        lines.set_linewidth(0.1)
        ax.add_collection(lines)
Esempio n. 30
0
def plot_gspan_res(G, subpref_id, color_val):
    
    fig = plt.figure(subpref_id)
    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
    ax = plt.subplot(111)
    
    m = Basemap(llcrnrlon=-9, \
                llcrnrlat=3.8, \
                urcrnrlon=-1.5, \
                urcrnrlat = 11, \
                resolution = 'h', \
                projection = 'tmerc', \
                lat_0 = 7.38, \
                lon_0 = -5.30)
   
    # read the shapefile archive
    s = m.readshapefile('/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE', 'subpref')
    
    m.drawcoastlines()
    
    shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    
    msg = "Out of bounds"
    color_col = []
    
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []
        
        
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
            x, y = m(lons, lats)
            shpsegs.append(zip(x,y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            #print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id2 = shapedict["ID_SP"]
            #color_col
            
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring+1
            shapedict['SHAPENUM'] = npoly+1
            shpinfo.append(shapedict)

        lines = LineCollection(shpsegs,antialiaseds=(1,))
        if subpref_id == subpref_id2:
            lines.set_facecolors('g')
        lines.set_edgecolors('k')
        lines.set_linewidth(0.3)
        ax.add_collection(lines)

    # data to plot on the map    
    lons = [int]*256
    lats = [int]*256
    num = []
    
    # read in coordinates fo subprefs
    file_name2 = "/home/sscepano/DATA SET7S/D4D/SUBPREF_POS_LONLAT.TSV"
    f2 = open(file_name2, 'r')
    
    # read subpref coordinates
    subpref_coord = {}
    for line in f2:
        subpref_id, lon, lat = line.split('\t')
        lon = float(lon)
        lat = float(lat)
        subpref_id = int(subpref_id)
        subpref_coord.keys().append(subpref_id)
        subpref_coord[subpref_id] = (lon, lat)
    
    f2.close()
    
    # if wanna plot number of users whose this is home subpref
    for subpref in range(1,256):
        lons[subpref] = subpref_coord[subpref][0]
        lats[subpref] = subpref_coord[subpref][1]
    

    for u, v, d in G.edges(data=True):
        lo = []
        la = []   
        lo.append(lons[u])
        lo.append(lons[v])
        la.append(lats[u])
        la.append(lats[v])
        x, y = m(lo, la)
        m.plot(x,y, color = color_val)


    return plt
Esempio n. 31
0
    rings = len(verts)
    for ring in range(rings):
        lons, lats = zip(*verts[ring])
        x, y = m(lons, lats)
        shpsegs.append(zip(x,y))
        if ring == 0:
            shapedict = dbf.read_record(npoly)
        print shapedict
        name = shapedict["ID_DEPART"]
        subpref_id = shapedict["ID_SP"]
        num = ["%.2f" % traj[subpref_id]]
#        for name, xc, yc in zip(num, x, y):
#            plt.text(xc, yc, name)
        #color_col
        
        # add information about ring number to dictionary.
        shapedict['RINGNUM'] = ring+1
        shapedict['SHAPENUM'] = npoly+1
        shpinfo.append(shapedict)
    #print subpref_id
    #print name
    lines = LineCollection(shpsegs,antialiaseds=(1,))
    lines.set_facecolors(str(1 - traj[subpref_id]))
    lines.set_edgecolors('k')
    lines.set_linewidth(0.3)
    ax.add_collection(lines)

    
#plt.savefig('/home/sscepano/D4D res/allstuff/CLUSTERING/subpref res/maps/grayscale_pct_home_c_map2.png',dpi=1000)
plt.show()
Esempio n. 32
0
    squarecorner = squareprolist[plotsquareCount].cornerPoints
    shadowlons = [
        squarecorner[0].x, squarecorner[1].x, squarecorner[2].x,
        squarecorner[3].x
    ]
    shadowlats = [
        squarecorner[0].y, squarecorner[1].y, squarecorner[2].y,
        squarecorner[3].y
    ]
    x, y = m(shadowlons, shadowlats)
    shpsegs = []
    shpsegs.append(list(zip(x, y)))
    lines = LineCollection(shpsegs, antialiaseds=(1, ))
    #不可航行区域
    if (squareprolist[plotsquareCount].isNavigonal == False):
        lines.set_facecolors(cm.jet(0.1))
        lines.set_edgecolors('g')
        lines.set_linewidth(0.6)
        lines.set_alpha(0.6)  #设置透明度
        ax.add_collection(lines)  #绘制不可行区域
    else:
        lines.set_facecolors(cm.jet(0.02))
        lines.set_edgecolors('b')
        lines.set_linewidth(1.2)
        #lines.set_alpha(0.1) #设置透明度

        # 设置颜色深度,权重越大深度越大
        weight = Naviweight.get(squareprolist[plotsquareCount].offsetCoord, 1)
        if weight < 1:
            weight = 1
        if weight > 10:
Esempio n. 33
0
shp = ShapeFile('.../states/statessp020')
dbf = dbflib.open('../states/statessp020')

for npoly in range(shp.info()[0]):
    # 在地图上绘制彩色多边形
    shpsegs = []
    shp_object = shp.read_object(npoly)
    verts = shp_object.vertices()
    rings = len(verts)
    for rings in range(rings):
        lons, lats = zip(*verts[ring])
        x, y = m(lons, lats)
        shpsegs.append(zip(x, y))
        if ring == 0:
            shapedict = dbf.read_record(npoly)
        name = shapedict['STATE']
    lines = LineCollection(shpsegs, antialiaseds=(1, ))

    # state_to_code字典,例如'ALASKA' -> 'AK', omitted
    try:
        per = obama[state_to_code[name.upper()]]
    except KeyError:
        continue

    lines.set_facecolors('k')
    lines.set_alpha(0.75 * per)
    lines.set_edgecolors('k')
    lines.set_linewidth(0.3)
plt.show()
Esempio n. 34
0
    rings = len(verts)
    for ring in range(rings):
        lons, lats = zip(*verts[ring])
#        if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
#            raise ValueError,msg
        x, y = m(lons, lats)
        shpsegs.append(zip(x,y))
        if ring == 0:
            shapedict = dbf.read_record(npoly)
        #print shapedict
        name = shapedict["ID_DEPART"]
        subpref_id = shapedict["ID_SP"]
        #color_col
        
        # add information about ring number to dictionary.
        shapedict['RINGNUM'] = ring+1
        shapedict['SHAPENUM'] = npoly+1
        shpinfo.append(shapedict)
    #print subpref_id
    #print name
    lines = LineCollection(shpsegs,antialiaseds=(1,))
    lines.set_facecolors(col[subpref_id])
    lines.set_edgecolors('k')
    lines.set_linewidth(0.3)
    ax.add_collection(lines)
    
plt.savefig('/home/sscepano/D4D res/allstuff/simple dynamics/v1/cleaned_mod_v1.png',dpi=1000)
#plt.show()

###################################################################################################3
            
Esempio n. 35
0
def map_fq(fq_scaled):
    
    print fq_scaled
    
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    
    import matplotlib as mpl
    mpl.rcParams['font.size'] = 10.
    mpl.rcParams['axes.labelsize'] = 8.
    mpl.rcParams['xtick.labelsize'] = 6.
    mpl.rcParams['ytick.labelsize'] = 6.
    
    fig = plt.figure(1)
    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
    ax = plt.subplot(111)
    
    m = Basemap(llcrnrlon=-9, \
                    llcrnrlat=3.8, \
                    urcrnrlon=-1.5, \
                    urcrnrlat = 11, \
                    resolution = 'h', \
                    projection = 'tmerc', \
                    lat_0 = 7.38, \
                    lon_0 = -5.30)
    
    m.drawcoastlines()
    
    from shapelib import ShapeFile
    import dbflib
    from matplotlib.collections import LineCollection
    from matplotlib import cm
    
    shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    
    msg = "Out of bounds"
    color_col = []
    
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []
        
        
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
            x, y = m(lons, lats)
            shpsegs.append(zip(x,y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            #num = ["%.2f" % data[subpref_id]]
    #        for name, xc, yc in zip(num, x, y):
    #            plt.text(xc, yc, name)
            #color_col
            
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring+1
            shapedict['SHAPENUM'] = npoly+1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs,antialiaseds=(1,))
        #print float("%.7f" % fq_scaled[subpref_id])
        lines.set_facecolors(str(1.0 - fq_scaled[str(subpref_id)]))
        lines.set_edgecolors('k')
        lines.set_linewidth(0.3)
        ax.add_collection(lines)
    
        
    plt.savefig('/home/sscepano/D4D res/allstuff/CLUSTERING/subpref no home res/scaled_subpref_Calling_fq2.png',dpi=1000)
    #plt.show()
    
    return
Esempio n. 36
0
        if ring == 0:
            shapedict = dbf.read_record(npoly)
        #print shapedict
        name = shapedict["ID_DEPART"]
        subpref_id = shapedict["ID_SP"]
        #color_col
        
        # add information about ring number to dictionary.
        shapedict['RINGNUM'] = ring+1
        shapedict['SHAPENUM'] = npoly+1
        shpinfo.append(shapedict)
    #print subpref_id
    #print name
    lines = LineCollection(shpsegs,antialiaseds=(1,))
    if subpref_cluster3[subpref_id] == 1:
        lines.set_facecolors('r')
    if subpref_cluster3[subpref_id] == 2:
        lines.set_facecolors('b')
    if subpref_cluster3[subpref_id] == 3:
        lines.set_facecolors('g')
    lines.set_edgecolors('k')
    lines.set_linewidth(0.3)
    ax.add_collection(lines)
    
plt.savefig('/home/sscepano/D4D res/allstuff/CLUSTERING/res/maps/pca/kmeans10args_3clusters.png',dpi=1000)
#plt.show()

###################################################################################################3

subpref_cluster2 = rd.read_in_subpref_assigned_2clusters() 
Esempio n. 37
0
def map_communities_and_commutes(G):
    
    G_mod = nx.read_gml("/home/sscepano/D4D res/allstuff/User movements graphs/commuting patterns/1/total_commuting_G_scaled_weights_11COM_713_7115.gml")
    
    col = [str]*256
    for i in range(256):
        col[i] = 'w'
    
    for node in G_mod.nodes_iter(data=True):
        #print node[1]['label']
        col_gephi = node[1]['graphics']['fill']
        while (len(col_gephi) < 7):
            col_gephi += '0'
        subpref_gephi = int(float(node[1]['label']))
        print subpref_gephi, col_gephi
        col[subpref_gephi] = col_gephi   
    #print col
    
    plt.clf()
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
    ax = plt.subplot(111)
    
    m = Basemap(llcrnrlon=-9, \
                llcrnrlat=3.8, \
                urcrnrlon=-1.5, \
                urcrnrlat = 11, \
                resolution = 'h', \
                projection = 'tmerc', \
                lat_0 = 7.38, \
                lon_0 = -5.30)
   
    # read the shapefile archive
    s = m.readshapefile('/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE', 'subpref')
    
    from shapelib import ShapeFile
    import dbflib
    from matplotlib.collections import LineCollection
    from matplotlib import cm
    
    shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []  
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
            x, y = m(lons, lats)
            shpsegs.append(zip(x,y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            #print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring+1
            shapedict['SHAPENUM'] = npoly+1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs,antialiaseds=(1,))
        lines.set_facecolors(col[subpref_id])
        lines.set_edgecolors('gray')
        lines.set_linewidth(0.3)
        ax.add_collection(lines)
    
    m.drawcoastlines()
    
    plt.show()

#    # data to plot on the map    
#    lons = [int]*256
#    lats = [int]*256
#    
#    # read in coordinates fo subprefs
#    file_name2 = "/home/sscepano/DATA SET7S/D4D/SUBPREF_POS_LONLAT.TSV"
#    f2 = open(file_name2, 'r')
#    
#    # read subpref coordinates
#    subpref_coord = {}
#    for line in f2:
#        subpref_id, lon, lat = line.split('\t')
#        lon = float(lon)
#        lat = float(lat)
#        subpref_id = int(subpref_id)
#        subpref_coord.keys().append(subpref_id)
#        subpref_coord[subpref_id] = (lon, lat)
#    
#    f2.close()
#    
#    # if wanna plot number of users whose this is home subpref
#    for subpref in range(1,256):
#        lons[subpref] = subpref_coord[subpref][0]
#        lats[subpref] = subpref_coord[subpref][1]
#    
#    
#    if G.has_node(-1): 
#        G.remove_node(-1)
#
#    max7s = 1
#    min7s = 1
#    for u,v,d in G.edges(data=True):
#        if d['weight'] > max7s:
#            max7s = d['weight']
#        if d['weight'] < min7s:
#            min7s = d['weight']
#            
#    max7s = float(max7s)
#    print max7s
#    print min7s
#    
#    scaled_weight = defaultdict(int)
#    for i in range(256):
#        scaled_weight[i] = defaultdict(int)
#    
#    for u,v,d in G.edges(data=True):
#        node1 = G.nodes(data=True)[u][1]['label']
#        node2 = G.nodes(data=True)[v][1]['label']
#        print u, node1
#        print v, node2
#        print d
#        scaled_weight[node1][node2] = (d['weight'] - min7s) / (max7s - min7s)
#        
##    for u,v,d in G.edges(data=True):
##        print u,v,d
##        node1 = G.nodes(data=True)[u][1]['label']
##        node2 = G.nodes(data=True)[v][1]['label']
##        print node1, G_mod.nodes(data=True)[u][1]['label']
##        print node2, G_mod.nodes(data=True)[v][1]['label']
#    
# 
#    for u, v, d in G.edges(data=True):
#        node1 = G.nodes(data=True)[u][1]['label']
#        node2 = G.nodes(data=True)[v][1]['label']
#        print node1
#        print node2
#        lo = []
#        la = []   
#        print u
#        print v
#        lo.append(lons[node1])
#        lo.append(lons[node2])
#        la.append(lats[node1])
#        la.append(lats[node2])
#        #m.drawgreatcircle(lons[u],lats[u], lons[v],lats[v])
#        x, y = m(lo, la)
#        #linewidth7s = d['weight']
#        #linewidth7s = d['weight'] / max7s
#        #lons, lats = n.meshgrid(lo,la)
#        linewidth7s = scaled_weight[node1][node2] * 7 + 0.2
#        m.plot(x,y, 'b', linewidth = linewidth7s)
#        #wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons))
#        #mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.)
#        #m.contour(x,y,linewidth=linewidth7s)
#        #m.quiver(x,y,lons, lats, latlon=True)
##        if linewidth7s > 1:
##            print linewidth7s
#        
#     
#    figure_name = "/home/sscepano/D4D res/allstuff/User movements graphs/commuting patterns/1/maps/mod_classes_SCALED_11COM_713_7115.png"
#    print(figure_name)
#    plt.savefig(figure_name, format = "png",dpi=1000) 
    
    return
    # print(record)
    # faire plus beau
    if record[6] == "Alpes-de-Haute-Provence":
        name = "Alpes-Hte-Provence"
    elif record[6] == "Territoire de Belfort":
        name = "Terr. de Belfort"
    elif record[6] == "Seine-Saint-Denis":
        name = "Seine-St-Denis"
    elif record[6] == "Paris":
        name = "Paris (Ville)"
    else:
        name = record[6]
    print("rec : ", name)
    # erreurs pour (dans rec):
    #   - Alpes-de-Haute-Provence -> Alpes-Hte-Provence
    #   - Territoire de Belfort -> Terr. de Belfort
    #   - Seine-Saint-Denis -> Seine-St-Denis
    #   - Paris -> Paris (Ville)


    dep = df.loc[df['DEPARTEMENT'] == name]
    print(dep['DEP/TOT'])
    dens = 0
    colorVal = scalarMap.to_rgba(dep['DEP/TOT'])
    lines.set_facecolors(colorVal)
    lines.set_edgecolors('k')
    lines.set_linewidth(0.1)
    ax.add_collection(lines)

plt.savefig('france2.png', dpi=300)
plt.show()
dbf = dbflib.open('../states/statesp020')

for npoly in range(shp.info()[0]):
    # draw colored polygons on the map
    shpseqs = []
    shp_object = shp.read_object(npoly)
    verts = shp_object.vertices()
    rings = len(verts)
    for ring in range(rings):
        lons, lats = zip(*verts[ring])
        x, y = m(lons,lats)
        shpsegs.append(zip(x,y))
        if ring == 0:
            shapedict = dbf.read_record(npoly)
        name = shapedict['STATE']
    lines = LineCollection(shpsegs,antialiased=(1,))

    # state_to_code dict, e.g. 'ALASKA' -> 'AK', omitted
    try:
        per = obama[state_to_code[name.upper()]]
    except KeyError:
        continue

    lines.set_facecolors('k')
    lines.set_alpha(0.75 * per) # shrink the percentage a bit
    lines.set_edgecolors('k')
    lines.set_linewidth(0.3)
    ax.add_collection(lines)

plt.show()
Esempio n. 40
0
def map_diversity():
    
    #subpref_avg_fq = rd.read_in_subpref_avg_fq()
    rg = get_scaled_rg()
     
    fig = plt.figure(1)
    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
    ax = plt.subplot(111)
    
    m = Basemap(llcrnrlon=-9, \
                    llcrnrlat=3.8, \
                    urcrnrlon=-1.5, \
                    urcrnrlat = 11, \
                    resolution = 'h', \
                    projection = 'tmerc', \
                    lat_0 = 7.38, \
                    lon_0 = -5.30)
    
    m.drawcoastlines()
    
    from shapelib import ShapeFile
    import dbflib
    from matplotlib.collections import LineCollection
    from matplotlib import cm
    
    shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    
    msg = "Out of bounds"
    color_col = []
    
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []
        
        
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
            x, y = m(lons, lats)
            shpsegs.append(zip(x,y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            #print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            num = ["%.2f" % rg[subpref_id]]
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring+1
            shapedict['SHAPENUM'] = npoly+1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs,antialiaseds=(1,))
        lines.set_facecolors(str(rg[subpref_id]))
        lines.set_edgecolors('k')
        lines.set_linewidth(0.3)
        ax.add_collection(lines)
    
    plt.savefig('/home/sscepano/D4D res/allstuff/diversity of travel/diversity_map.png',dpi=500)
    
    return
Esempio n. 41
0
	        segs = [data,]
	    else:
	        segs = []
	        for i in range(1,len(shape.parts)):
	            index = shape.parts[i-1]
	            index2 = shape.parts[i]
	            segs.append(data[index:index2])
	        segs.append(data[index2:])
 
	    lines = LineCollection(segs,antialiaseds=(1,))
	    #Now obtain the data in a given poly and assign a color to the value
	    div = str(record[5])
	    #print record
	    dval = divlookup(dfile,div,yyyy,int(mm))
	    #if(dval > valmax): dval = valmax - 0.1
	    lines.set_facecolors(cmap_temp([dval/cwidth]))
	    lines.set_edgecolors(cmap_temp([dval/cwidth]))
	    lines.set_linewidth(0.25)
	    ax1.add_collection(lines)

if(imgsize == 'GEO'):
	inProj = Proj(init='epsg:3338')
	outProj = Proj(init='epsg:4326')
	#Now read in the Alaska Climate Division Shapes and fill the basemap 
	s = shapefile.Reader(r"./Shapefiles/AK_divisions_NAD83")
	shapes = s.shapes()
	records = s.records()
	

	for record, shape in zip(records,shapes):
	    lons,lats = zip(*shape.points)
Esempio n. 42
0
    lons,lats = zip(*shape.points)
    data = np.array(m(lons, lats)).T

    if len(shape.parts) == 1:
        segs = [data,]
    else:
        segs = []
        for i in range(1,len(shape.parts)):
            index = shape.parts[i-1]
            index2 = shape.parts[i]
            segs.append(data[index:index2])
        segs.append(data[index2:])

    lines = LineCollection(segs,antialiaseds=(1,))
    lines.set_facecolors(np.random.rand(3, 1) * 0.5 + 0.5)
    lines.set_edgecolors('k')
    lines.set_linewidth(0.1)
    ax.add_collection(lines)
    cnt += 1


infile = open(curdir +'state_info_revised.csv','r')
csvfile = csv.reader(infile)



for lakepoly in m.lakepolygons:
    lp = Polygon(lakepoly.boundary, zorder=3)
    lp.set_facecolor(thisblue)
    lp.set_linewidth(0.1)
Esempio n. 43
0
    ## within this loop, we will also check that the shape is not in multiple parts, and if yes, segment the points in different ensembles:

    if sovereignt == 'Uganda':
        color = '#2b8cbe'
    else:
        color = '#a6bddb'
        continue

    if len(shape.parts) == 1:
        segs = [
            data,
        ]
    else:
        segs = []
        for i in range(1, len(shape.parts)):
            index = shape.parts[i - 1]
            index2 = shape.parts[i]
            segs.append(data[index:index2])
        segs.append(data[index2:])

    lines = LineCollection(segs, antialiaseds=(1, ))
    lines.set_facecolors(color)
    lines.set_edgecolors('k')
    lines.set_linewidth(0.1)
    ax.add_collection(lines)

m.drawcoastlines(linewidth=0.5)

plt.savefig('map.png', dpi=600)
plt.close()
Esempio n. 44
0
    def choropleth(self,
                   adm_num_dicts,
                   level='department',
                   source='gadm',
                   cmap_base=plt.cm.YlOrRd,
                   ret_colormap_and_label=True,
                   bin_lims=None,
                   nbins=5,
                   linewidth=0.4):
        """
        A choropleth map by department  or municipality. The dataset for boundaries of administrative areas is taken from GADM database 
        Original code is from here: https://github.com/astivim/Nicaragua-Population-Density-Map    
        
        Input:
        - adm_num_dicts: a list of dictionaries with the following key-value pairs: {'adm' : str, 'num' : float}
        - bin_lims (optional): values of bin edges
        - nbins (optional): number of bins, default = 5. Ignored if bin_lims is specified. 
        - cmap_base: base colormap. Default is plt.cm.YlOrRd (red)  
        - ret_colormap_and_label=True. If True, return colormap_label = {'bin_labels' : bin_labels, 'colormap' : custom_cmap} used for plotting. If False, colormap_label = None  

        Return: colormap_label = {'bin_labels' : bin_labels, 'colormap' : custom_cmap}
        """
        # Divide nums into bins. For each entry in nums, assign to which bin it belongs to, then assign a color to each bin.

        adms = [item['adm'] for item in adm_num_dicts]
        nums = [item['num'] for item in adm_num_dicts]

        # Define bin_lims by dividing the range of nums into equally spaced portions
        if bin_lims:
            nbins = len(bin_lims)
        else:
            temp_nums = [num for num in nums if num]
            bin_spacing = (max(temp_nums) - min(temp_nums) + 1) / nbins
            bin_lims = np.arange(min(temp_nums),
                                 max(temp_nums) + bin_spacing, bin_spacing)
            nbins = len(bin_lims)

        # Assign each num in nums into its respective bin and assign color. Use only nbins values from the colormap (cmap)
        nums_bin_ix = np.digitize(nums, bin_lims)
        nums_bin_ix = [idx if idx < nbins else 0 for idx in nums_bin_ix]
        cmaplist = [cmap_base(i) for i in range(cmap_base.N)]
        del_colors = np.int(np.ceil(cmap_base.N / float(nbins - 1)))
        map_colors = cmaplist[0::del_colors]
        map_colors.insert(
            0,
            (1.0, 1.0, 1.0, 1.0))  # fill with white if no data (num is None)

        # Load the geographical data (shapefile and record)
        if level == 'department':
            fpath = os.path.join(self.data_dir, "NIC_adm/NIC_adm1")
        elif level == 'municipality':
            fpath = os.path.join(self.data_dir, "NIC_adm/NIC_adm2")
        else:
            print("Level unrecognized. Use 'department'")
            fpath = os.path.join(self.data_dir, "NIC_adm/NIC_adm1")

        r = shapefile.Reader(fpath)
        shapes = r.shapes()
        records = r.records()

        # Extract lat and lon data from the GADM shapefile and assign a facecolor to each department
        for record, shape in zip(records, shapes):
            lons, lats = zip(*shape.points)
            data = [(lon, lat) for lon, lat in zip(*self(lons, lats))]
            if level == 'department':
                adm_name = record[4]
            else:
                adm_name = record[6]

            try:
                adm_idx = adms.index(adm_name)
                adm_num = adm_num_dicts[adm_idx]['num']
                color_idx = nums_bin_ix[adm_idx]
            except ValueError:
                adm_num = None
                color_idx = 0

            if len(shape.parts) == 1:
                segs = [
                    data,
                ]
            else:
                segs = []
                for i in range(1, len(shape.parts)):
                    index = shape.parts[i - 1]
                    index2 = shape.parts[i]
                    segs.append(data[index:index2])

                segs.append(data[index2:])
            lines = LineCollection(segs, antialiaseds=(1, ))

            color = map_colors[color_idx] if adm_name not in [
                "Lago Nicaragua", "Lago de Nicaragua"
            ] else 'aqua'
            lines.set_facecolors(color)
            lines.set_linewidth(linewidth)
            self.ax.add_collection(lines)

        if ret_colormap_and_label:
            custom_cmap = mpl.colors.ListedColormap(map_colors[1:],
                                                    name='from_list')
            bins = [(i1, i2)
                    for i1, i2 in zip(bin_lims[0:nbins], bin_lims[1:nbins + 1])
                    ]
            bin_labels = ["(%d - %d)" % (b[0], b[1]) for b in bins]
            colormap_label = {
                'bin_labels': bin_labels,
                'colormap': custom_cmap
            }
        else:
            colormap_label = None

        return colormap_label