def draw_map(lat, lng, sic):
    # setup south polar stereographic basemap.
    # The longitude lon_0 is at 6-o'clock, and the
    # latitude circle boundinglat is tangent to the edge
    # of the map at lon_0. Default value of lat_ts
    # (latitude of true scale) is pole.
    m = Basemap(projection='spstere',boundinglat=-50,lon_0=270,resolution='h', round=True)
    # Basemap()
  
    plt.figure()
    for beam in range(8):        
        x1,y1 = m(lng[beam], lat[beam])
        m.hexbin(x1,y1, C=sic[beam],gridsize=len(sic[beam]),cmap=plt.cm.jet)
            
    m.drawcoastlines()
    m.fillcontinents(color='coral',lake_color='aqua')
    # draw parallels and meridians.
    m.drawparallels(np.arange(-80.,81.,20.))
    m.drawmeridians(np.arange(-180.,181.,20.))
    m.drawmapboundary(fill_color='aqua')
    
    m.colorbar(location="bottom",label="SIC") # draw colorbar
    plt.title("North Polar Stereographic Projection")
    plt.gcf().set_size_inches(18,10)
    plt.show()
def hexagon_map(coordinates, temperature, hex_grid_size=(50,50)):
    m = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
    m.drawcoastlines()
    m.drawcountries()
    m.drawmapboundary()
    lats = coordinates[:,0]
    lons = coordinates[:,1]
    x, y  = m(lons, lats)
    m.hexbin(x, y, C = temperature, gridsize=hex_grid_size, linewidth=0.5, edgecolor='k')
    m.colorbar(location='bottom')
    plt.show()
Example #3
0
  def drawHk(self, filename="nodet"):
 
     #    print sic
     # setup south polar stereographic basemap.
     if (len(self)!=0):
          m = Basemap(projection='spstere',boundinglat=-50,lon_0=180,resolution='h', round=True)
      
      
          lat = []
          lng = []
          sic = []
          
          for s in self:
              lng.append(s.getLon())
              lat.append(s.getLat())
              sic.append(s.getSic())
          
      
          lng = np.array(lng)
          lat = np.array(lat)
          sic = np.array(sic)
          plt.figure()
     
          x1,y1= m(lng, lat)
     
          print "x, y, sic", x1, y1, sic
          m.hexbin(x1,y1, C=sic, gridsize=len(sic), cmap=plt.cm.jet)
  
     
          m.drawcoastlines()
          m.fillcontinents(lake_color='white')
          # draw parallels and meridians.
          m.drawparallels(np.arange(-80.,81.,20.))
          m.drawmeridians(np.arange(-180.,181.,20.))
          m.drawmapboundary(fill_color='green')
  
      
          m.colorbar(location="right",label="SIC") # draw colorbar
          plt.title("Sea Ice Concentration - South Pole")
          fig = plt.gcf()
          plt.show()
          f_name = "./img/"+filename + "_.png"
          fig.savefig(f_name)
          plt.close()
          
          # Delete auxiliar variables.
          del m
          del lng    
          del lat    
          del sic    
          del x1
          del y1
          
          return f_name
Example #4
0
def station_map(coordinates, temperature):
#    map = Basemap(projection='lcc', lat_0 = 51, lon_0 = 10, resolution = 'i', width = 850000, height = 1000000)
    map = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
    map.drawcoastlines()
    map.drawcountries()
    map.drawmapboundary()
    lats = coordinates[:,0]
    lons = coordinates[:,1]
    x, y  = map(lons, lats)
#    map.hexbin(x,y)
    map.hexbin(x, y, C = temperature, gridsize=(9,9), linewidth=0.5, edgecolor='k')
    map.colorbar(location='bottom')
    plt.show()
def hexagon_map(coordinates, temperature, hex_grid_size=(50,50)):
    m = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
    lats = coordinates[:,0]
    lons = coordinates[:,1]
    x, y  = m(lons, lats)
    plt.ion()
    for i in range(len(temperature)):
        plt.clf()
        m.drawcoastlines()
        m.drawcountries()
        m.drawmapboundary()
        m.hexbin(x, y, C = temperature[:,i], gridsize=hex_grid_size, linewidth=0.5, edgecolor='k', vmin=np.amin(temperature), vmax=np.amax(temperature))
        cb = m.colorbar(location='bottom', label='Random data')
        plt.show()
        plt.pause(0.005)
Example #6
0
    def drawHkNPole(self, filename="nodet"):
        if (len(self)!=0):
            ms = Basemap(projection='npstere',boundinglat=50,lon_0=180,resolution='h', round=True)
            lat = []
            lng = []
            sic = []
            for s in self:
                lng.append(s.getLon())
                lat.append(s.getLat())
                sic.append(s.getSic())
                #print s.getLat(), s.getLon(), s.getSic()                 
                
            lng = np.array(lng)
            lat = np.array(lat)
            sic = np.array(sic)
            
            plt.figure()
            x1,y1= ms(lng, lat) 
            ms.hexbin(x1,y1, C=sic, gridsize=len(sic), cmap=plt.cm.jet)
            
            ms.drawcoastlines()
            ms.fillcontinents(lake_color='green')
            ms.drawparallels(np.arange(-80.,81.,20.))
            ms.drawmeridians(np.arange(-180.,181.,20.))
            ms.drawmapboundary(fill_color='white')
            ms.colorbar(location="right",label="SIC") # draw colorbar            
            
            plt.title("Sea Ice south Concentration")
            fig = plt.gcf()
            plt.show()
            f_name = "./img/"+filename + "S.png"
            fig.savefig(f_name)
            
            plt.close()
            
            
            del ms

            del lng    
            del lat    
            del sic    
            del x1
            del y1
            
            return f_name
Example #7
0
def hexagon_map(station_lon, station_lat, station_val, hex_grid_size=(50,50)):
    """
    Creates a map of values for different stations, using hexagons per station location.

    Params:
        station_lon (1D arrya): longitutes of station locations
        station_lat (1D arrya): latitudes of station locations
        station_val (1D arrya): values to plot per stations
        hex_grid_size (tuple, optional): number of hexagons in x and y dimension
    """

    m = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
    #with open('germany_map.pkl', 'rb') as input:
        #m = pickle.load(input) # open map from disk
    m.drawcoastlines()
    m.drawcountries()
    m.drawmapboundary()
    x, y  = m(station_lon, station_lat)
    m.hexbin(x, y, C = station_val, gridsize=hex_grid_size, linewidth=0.5, edgecolor='k', vmin=np.nanmin(station_val), vmax=np.nanmax(station_val))
    #m.colorbar(location='bottom')
    cb = m.colorbar(location='bottom', label='Random Data', ticks=[np.nanmin(station_val), 0,  np.nanmax(station_val)])
    plt.show()
Example #8
0
 def drawNPole(self):
     m = Basemap(projection='npstere',boundinglat=50,lon_0=270,resolution='h', round=True)    
 
     if (len(self._lats)==0):
         self._fillvalues()
         
         
     lng = self.getLonAsNp()
     lat = self.getLatAsNp() 
     sic = self.getSicAsNp()
     
     plt.figure()
        
     x1,y1= m(lng, lat)
        
     m.hexbin(x1,y1, C=sic, gridsize=len(sic), cmap=plt.cm.jet)
     
     m.drawcoastlines()
     m.drawcountries()
     m.fillcontinents(color='coral')
     m.drawmapboundary()
     # draw parallels and meridians.
     #m.drawparallels(np.arange(-80.,81.,20.))
     #m.drawmeridians(np.arange(-180.,181.,20.))
     #m.drawmapboundary(fill_color='white')
     #m.colorbar(location="right",label="SIC") # draw colorbar
     plt.title("Final")
     #fig = plt.gcf()
     plt.show()
     plt.close()
     # Delete auxiliar variables.
     del m
     del lng    
     del lat    
     del sic    
     del x1
     del y1
    
    flash_lat = np.concatenate([flash_lat,datafile.variables['lightning_flash_lat'][:]]) #add to array
    flash_lon = np.concatenate([flash_lon,datafile.variables['lightning_flash_lon'][:]]) #add to array


#Create CSV files of values from the populated flash_lat/lon arrays  
with open(csvfile, 'wb') as myfile:
    writer = csv.writer(myfile)
    writer.writerows(izip(["flash_lat"], ["flash_lon"])) #Define headers in row (izip creates columns)
    writer.writerows(izip(flash_lat,flash_lon)) #Define data rows (izip creates columns)


#Create plot of lightning flash location heat map
plt.figure(figsize=((20,20))) #Set plot dimensions
map = Basemap(projection='cyl', lon_0 = 0, resolution='c')
lightning = map.hexbin(flash_lon, flash_lat, gridsize=300,bins='log',cmap='jet',mincnt=1,zorder=10) #Bin flash counts into hexbins using a gridsize of your choice

#Draw geographic boundaries and meridians/parallels
map.drawmapboundary(fill_color='k')
map.fillcontinents(color='grey',lake_color='grey')
map.drawcoastlines(color='white')
map.drawcountries(color='white')
map.drawmeridians(np.arange(0,390,30), labels=[0,0,0,1],fontsize=10, color="lightgray")
map.drawparallels(np.arange(-90,120,30), labels=[1,0,0,0],fontsize=10, color="lightgray")

cbar = map.colorbar(lightning,location='bottom',pad="5%")
cbar.set_label('Flash Count') #Remember to change label

plt.title('ISS LIS Detected Lightning Flash Locations January 4, 2018', fontsize = 18) #Rember to change title

Example #10
0
lats = np.compress(lats > 20, lats)
lons = np.compress(lats > 20, lons)
# convert to map projection coordinates.
x1, y1 = m(lons, lats)
# remove points outside projection limb.
x = np.compress(np.logical_or(x1 < 1.e20, y1 < 1.e20), x1)
y = np.compress(np.logical_or(x1 < 1.e20, y1 < 1.e20), y1)
# function to plot at those points.
xscaled = 4. * (x - 0.5 * (m.xmax - m.xmin)) / m.xmax
yscaled = 4. * (y - 0.5 * (m.ymax - m.ymin)) / m.ymax
z = xscaled * np.exp(-xscaled**2 - yscaled**2)

# make plot using hexbin
fig = plt.figure(figsize=(12, 5))
ax = fig.add_subplot(121)
CS = m.hexbin(x, y, C=z, gridsize=bins, cmap=plt.cm.jet)
# draw coastlines, lat/lon lines.
m.drawcoastlines()
m.drawparallels(np.arange(0, 81, 20))
m.drawmeridians(np.arange(-180, 181, 60))
m.colorbar()  # draw colorbar
plt.title('hexbin demo')

# use histogram2d instead of hexbin.
ax = fig.add_subplot(122)
# remove points outside projection limb.
bincount, xedges, yedges = np.histogram2d(x, y, bins=bins)
mask = bincount == 0
# reset zero values to one to avoid divide-by-zero
bincount = np.where(bincount == 0, 1, bincount)
H, xedges, yedges = np.histogram2d(x, y, bins=bins, weights=z)
Example #11
0
lats = np.compress(lats > 20, lats)
lons = np.compress(lats > 20, lons)
# convert to map projection coordinates.
x1, y1 = m(lons, lats)
# remove points outside projection limb.
x = np.compress(np.logical_or(x1 < 1.e20,y1 < 1.e20), x1)
y = np.compress(np.logical_or(x1 < 1.e20,y1 < 1.e20), y1)
# function to plot at those points.
xscaled = 4.*(x-0.5*(m.xmax-m.xmin))/m.xmax
yscaled = 4.*(y-0.5*(m.ymax-m.ymin))/m.ymax
z = xscaled*np.exp(-xscaled**2-yscaled**2)

# make plot using hexbin
fig = plt.figure(figsize=(12,5))
ax = fig.add_subplot(121)
CS = m.hexbin(x,y,C=z,gridsize=bins,cmap=plt.cm.jet)
# draw coastlines, lat/lon lines.
m.drawcoastlines()
m.drawparallels(np.arange(0,81,20))
m.drawmeridians(np.arange(-180,181,60))
m.colorbar() # draw colorbar
plt.title('hexbin demo')

# use histogram2d instead of hexbin.
ax = fig.add_subplot(122)
# remove points outside projection limb.
bincount, xedges, yedges = np.histogram2d(x, y, bins=bins)
mask = bincount == 0
# reset zero values to one to avoid divide-by-zero
bincount = np.where(bincount == 0, 1, bincount)
H, xedges, yedges = np.histogram2d(x, y, bins=bins, weights=z)
Example #12
0
    def plot(
            self, data, bbox=None, plot_type='scatter',
            fig_kwargs=None, bmap_kwargs=None, plot_kwargs=None,
            cbar_kwargs=None):
        """
        Plot an array of data on a map using matplotlib and Basemap,
        automatically matching the data to node positions.

        Keyword arguments are passed to the plotting routine.

        Parameters
        ----------
        data : pandas.Series
            Numeric data with the same length and index as the nodes
            in the network.
        bbox : tuple, optional
            (lat_min, lng_min, lat_max, lng_max)
        plot_type : {'hexbin', 'scatter'}, optional
        fig_kwargs : dict, optional
            Keyword arguments that will be passed to
            matplotlib.pyplot.subplots. Use this to specify things like
            figure size or background color.
        bmap_kwargs : dict, optional
            Keyword arguments that will be passed to the Basemap constructor.
            This can be used to specify a projection or coastline resolution.
        plot_kwargs : dict, optional
            Keyword arguments that will be passed to the matplotlib plotting
            command used. Use this to control plot styles and color maps used.
        cbar_kwargs : dict, optional
            Keyword arguments passed to the Basemap.colorbar method.
            Use this to control color bar location and label.

        Returns
        -------
        bmap : Basemap
        fig : matplotlib.Figure
        ax : matplotlib.Axes

        """
        from mpl_toolkits.basemap import Basemap

        fig_kwargs = fig_kwargs or {}
        bmap_kwargs = bmap_kwargs or {}
        plot_kwargs = plot_kwargs or {}
        cbar_kwargs = cbar_kwargs or {}

        if not bbox:
            bbox = (
                self.nodes_df.y.min(),
                self.nodes_df.x.min(),
                self.nodes_df.y.max(),
                self.nodes_df.x.max())

        fig, ax = plt.subplots(**fig_kwargs)

        bmap = Basemap(
            bbox[1], bbox[0], bbox[3], bbox[2], ax=ax, **bmap_kwargs)
        bmap.drawcoastlines()
        bmap.drawmapboundary()

        x, y = bmap(self.nodes_df.x.values, self.nodes_df.y.values)

        if plot_type == 'scatter':
            plot = bmap.scatter(
                x, y, c=data.values, **plot_kwargs)
        elif plot_type == 'hexbin':
            plot = bmap.hexbin(
                x, y, C=data.values, **plot_kwargs)

        bmap.colorbar(plot, **cbar_kwargs)

        return bmap, fig, ax

#translate lat lon into map coordinates (meters) based on map projection

points=zip(lon,lat)
points = convert_lon_lat_points_to_meters_using_transform(points, m.projtran)

#add points to map
#m.plot(x, y, 'ko', markersize=1)
#m.plot(points[:,0],points[:,1], 'ko', markersize=1)

#add alpha transparency to color ramp
# Choose colormap
import matplotlib.colors as mcolors
c = mcolors.ColorConverter().to_rgb
#adjusted color map for legibility
cmap = make_colormap([c('#FFFFFF'),c('#A83E3E'),0.5,c('#A83E3E'),c('#690303')])
#straight linear colormap
#cmap = make_colormap([c('white'),c('darkred')])

# make plot using hexbin
bins = 40
#CS = m.hexbin(x=points[:,0],y=points[:,1],C=points[:,2],gridsize=bins,cmap=cmap) #C=points[:,2] is messing it up, so changed solution
CS = m.hexbin(x=points[:,0],y=points[:,1],gridsize=bins,cmap=cmap) #without weighting -- weighting comes from list explosion
m.colorbar(location="bottom",label="mentions in bin") # draw colorbar

plt.title('Locations Mentioned in the Journal Day Voyages: 1880-p1')
plt.gcf().set_size_inches(8,5)
plt.show()

#    resolution='l')
m = Basemap(llcrnrlon=-145.5,
            llcrnrlat=1.0,
            urcrnrlon=-2.566,
            urcrnrlat=46.352,
            rsphere=(6378137.00, 6356752.3142),
            resolution='l',
            area_thresh=1000.0,
            projection='lcc',
            lat_1=50.0,
            lon_0=-107.0,
            ax=ax)
x, y = m(train['Longitude'].values, train['Latitude'].values)
m.drawcoastlines()
m.drawcountries()
m.hexbin(x, y, gridsize=1000, bins='log', cmap=cm.YlOrRd)

# # Using Kmeans-Clustering

# In[ ]:

latlon = train[['Longitude', 'Latitude']]
latlon.head()

# In[ ]:

kmeans = KMeans(n_clusters=50)
kmodel = kmeans.fit(latlon)
centroids = kmodel.cluster_centers_

# In[ ]:
Example #15
0
    def plot(self,
             data,
             bbox=None,
             plot_type='scatter',
             fig_kwargs=None,
             bmap_kwargs=None,
             plot_kwargs=None,
             cbar_kwargs=None):
        """
        Plot an array of data on a map using matplotlib and Basemap,
        automatically matching the data to node positions.

        Keyword arguments are passed to the plotting routine.

        Parameters
        ----------
        data : pandas.Series
            Numeric data with the same length and index as the nodes
            in the network.
        bbox : tuple, optional
            (lat_min, lng_min, lat_max, lng_max)
        plot_type : {'hexbin', 'scatter'}, optional
        fig_kwargs : dict, optional
            Keyword arguments that will be passed to
            matplotlib.pyplot.subplots. Use this to specify things like
            figure size or background color.
        bmap_kwargs : dict, optional
            Keyword arguments that will be passed to the Basemap constructor.
            This can be used to specify a projection or coastline resolution.
        plot_kwargs : dict, optional
            Keyword arguments that will be passed to the matplotlib plotting
            command used. Use this to control plot styles and color maps used.
        cbar_kwargs : dict, optional
            Keyword arguments passed to the Basemap.colorbar method.
            Use this to control color bar location and label.

        Returns
        -------
        bmap : Basemap
        fig : matplotlib.Figure
        ax : matplotlib.Axes

        """
        from mpl_toolkits.basemap import Basemap

        fig_kwargs = fig_kwargs or {}
        bmap_kwargs = bmap_kwargs or {}
        plot_kwargs = plot_kwargs or {}
        cbar_kwargs = cbar_kwargs or {}

        if not bbox:
            bbox = (self.nodes_df.y.min(), self.nodes_df.x.min(),
                    self.nodes_df.y.max(), self.nodes_df.x.max())

        fig, ax = plt.subplots(**fig_kwargs)

        bmap = Basemap(bbox[1],
                       bbox[0],
                       bbox[3],
                       bbox[2],
                       ax=ax,
                       **bmap_kwargs)
        bmap.drawcoastlines()
        bmap.drawmapboundary()

        x, y = bmap(self.nodes_df.x.values, self.nodes_df.y.values)

        if plot_type == 'scatter':
            plot = bmap.scatter(x, y, c=data.values, **plot_kwargs)
        elif plot_type == 'hexbin':
            plot = bmap.hexbin(x, y, C=data.values, **plot_kwargs)

        bmap.colorbar(plot, **cbar_kwargs)

        return bmap, fig, ax
Example #16
0
class Map:
    def __init__(self, connection):
        """constructor for Map object
        
        Args: 
            connection: database name
        """
        self.types = ["'THEFT'", "'BATTERY'", "'ARSON'", "'MOTOR VEHICLE THEFT'", "'CRIMINAL DAMAGE'",
                 "'ROBBERY'", "'BURGLARY'", "'ASSAULT'", "'NARCOTICS'", "'HOMICIDE'", "'OTHER OFFENSE'"]

        self.colors = {"'THEFT'": "#ff0000", "'BATTERY'": "#dfd03c", "'ARSON'": "green", "'MOTOR VEHICLE THEFT'": "brown", "'CRIMINAL DAMAGE'": "#c9752f",
                  "'ROBBERY'": "#652b2b", "'BURGLARY'": "#b23131", "'ASSAULT'": "#f0cf68", "'NARCOTICS'": "#990099", "'HOMICIDE'": "#ff00ff", "'OTHER OFFENSE'": "#61743f"}

        self.con = db.connect(connection)

    def load(self):
        """loads shapefile onto graphical representation of data using basemap and fiona"""
        shape = fiona.open("data/shapefiles/chicago.shp")
        bounds = shape.bounds
        extra = 0.01
        lower_left = (bounds[0], bounds[1])
        upper_right = (bounds[2], bounds[3])
        coords = list(chain(lower_left, upper_right))
        width, height = coords[2] - coords[0], coords[3] - coords[1]

        self.base_map = Basemap(
            projection="tmerc",
            lon_0=-87.,
            lat_0=41.,
            ellps="WGS84",
            llcrnrlon=coords[0] - extra * width,
            llcrnrlat=coords[1] - extra + 0.01 * height,
            urcrnrlon=coords[2] + extra * width,
            urcrnrlat=coords[3] + extra + 0.01 * height,
            lat_ts=0,
            resolution='i',
            suppress_ticks=True
        )

        self.base_map.readshapefile(
            "data/shapefiles/chicago",
            'chicago',
            color='none',
            zorder=2
        )

        self.data_map = pd.DataFrame({
            'poly': [Polygon(xy) for xy in self.base_map.chicago],
            'community_name': [ward['community'] for ward in self.base_map.chicago_info]})
        self.data_map['area_m'] = self.data_map['poly'].map(lambda x: x.area)
        self.data_map['area_km'] = self.data_map['area_m'] / 100000
        self.data_map['patches'] = self.data_map['poly'].map(lambda x: PolygonPatch(x,
                                                                                    fc='#555555',
                                                                                    ec='#787878', lw=.25, alpha=.9,
                                                                                    zorder=4))

        plt.close()
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111, axisbg='w', frame_on=False)

        self.ax.add_collection(PatchCollection(self.data_map['patches'].values, match_original=True))

        self.base_map.drawmapscale(
            coords[0] + 0.08, coords[1] + 0.015,
            coords[0], coords[1],
            10.,
            barstyle='fancy', labelstyle='simple',
            fillcolor1='w', fillcolor2='#555555',
            fontcolor='#555555',
            zorder=5)

    def gen_points(self, dataframe, map):
        """places points from coords in dataset onto a map
        
        Args: 
            dataframe: dataset to get coords from
            map: map
        """
        points = pd.Series(
            [Point(self.base_map(mapped_x, mapped_y)) for mapped_x, mapped_y in
             zip(dataframe['Longitude'], dataframe['Latitude'])])
        crimes = MultiPoint(list(points.values))

        polygons = prep(MultiPolygon(list(map['poly'].values)))
        return list(filter(polygons.contains, crimes))


    def show_hexbin(self, query):
        """shows hexbin plot over map
        
        Args: 
            query: name of sql
        """
        self.load()
        data = pd.read_sql_query(con=self.con, sql=query)
        points = self.gen_points(data, self.data_map)
        hx = self.base_map.hexbin(
            np.array([geom.x for geom in points]),
            np.array([geom.y for geom in points]),
            gridsize=275,
            bins='log',
            mincnt=1,
            edgecolor='none',
            alpha=1.,
            lw=0.2,
            cmap=plt.get_cmap('afmhot'))
        plt.tight_layout()
        plt.show()


    def show_scatter(self, query, color='blue'):
        self.load()
        """shows scatter plot over map
        
        Args: 
            query: name of sql
        """
        data = pd.read_sql_query(con=self.con, sql=query)
        points = self.gen_points(data, self.data_map)

        plot = self.base_map.scatter(
            [point.x for point in points],
            [point.y for point in points],
            10, marker='o', lw=.25,
            facecolor=color, edgecolor='w',
            alpha=0.9, antialiased=True,
            zorder=3)
        plt.show()

    def animate_scatter(self, year):
        """shows animated scatter plot over map
        
        Args: 
            year: year of crimes to select
        """
        plt.ion()
        self.load()
        self.base_map.scatter(
            x=[],
            y=[],
            s=3, marker='o', lw=.25,
            facecolor='#33ccff', edgecolor='w',
            alpha=0.9, antialiased=True,
            label='Chicago Crime Locations', zorder=3)

        plt.title("Crimes in Chicago")

        plots = []
        for i in range(1, 12):
            if i < 10:
                month = "0%d".format(i)
            else:
                month = str(i)
            for j in range(1, 30):
                if j < 10:
                    day = "0%d".format(j)
                else:
                    day = str(j)
                date = '"{0}-{1}-{2}"'.format(year, month, day)
                for t in self.types:
                    plt.pause(0.000001)
                    data = pd.read_sql_query(con=self.con, sql=MAP_QUERY.format("Data", t, date))
                    points = self.gen_points(data, self.data_map)

                    plot = self.base_map.scatter(
                        [point.x for point in points],
                        [point.y for point in points],
                        10, marker='o', lw=.25,
                        facecolor=self.colors[t], edgecolor='w',
                        alpha=0.9, antialiased=True,
                        zorder=3)
                    plots.append(plot)

                if len(plots) > 0:
                    for p in plots:
                        try:
                            p.remove()
                        except:
                            pass
        plt.ioff()


    def chloropleth(self, query, color = "Blues"):
        """shows a chloropleth map of crimes
        
        Args: 
            query: name of sql
        """
        self.load()
        data = pd.read_sql_query(con=self.con, sql=query)
        points = self.gen_points(data, self.data_map)
        self.data_map['count'] = self.data_map['poly'].map(lambda x: len(list(filter(prep(x).contains, points))))
        self.data_map['density_m'] = self.data_map['count'] / self.data_map['area_m']
        self.data_map['density_km'] = self.data_map['count'] / self.data_map['area_km']
        self.data_map.replace(to_replace={'density_m': {0: np.nan}, 'density_km': {0: np.nan}}, inplace=True)
    
        breaks = nb(
            self.data_map[self.data_map['density_km'].notnull()].density_km.values,
            initial=300,
            k=5)

        jb = pd.DataFrame({'jenks_bins': breaks.yb}, index=self.data_map[self.data_map['density_km'].notnull()].index)
        self.data_map = self.data_map.join(jb)
        self.data_map.jenks_bins.fillna(-1, inplace=True)

        jenks_labels = ["<= %0.1f/km$^2$(%s communities)" % (b, c) for b, c in zip(
            breaks.bins, breaks.counts)]
        jenks_labels.insert(0, 'None (%s communities)' % len(self.data_map[self.data_map['density_km'].isnull()]))
    
        cmap = plt.get_cmap(color)
        self.data_map['patches'] = self.data_map['poly'].map(lambda x: PolygonPatch(x, ec='#555555', lw=.2, alpha=1., zorder=4))
        pc = PatchCollection(self.data_map['patches'], match_original=True)
        norm = Normalize()
        pc.set_facecolor(cmap(norm(self.data_map['jenks_bins'].values)))
        self.ax.add_collection(pc)

        cb = self.gen_colorbar(colors=len(jenks_labels), color_map=cmap, shrink=0.5, labels=jenks_labels)
        cb.ax.tick_params(labelsize=6)

        plt.tight_layout()
        plt.show()

    def network(self, type, start, end, factor=1.0, color=None, src=None):
        """create network of crimes
        
        Args: 
            type: data type
            start: start character
            end: end character
            factor: size, default 1
            color: colour, default None
            src: default None
        """
        self.load()
        df = pd.read_sql_query(con=self.con, sql=GEN_SEARCH_QUERY.format("Data", "Type = '{0}' "
                                                                            "AND Latitude is NOT NULL "
                                                                            "AND Longitude is NOT NULL "
                                                                            "AND date(Date) > date('{1}') "
                                                                            "AND date(Date) <= date('{2}')".format(type,
                                                                                                                   start,
                                                                                                                   end)))


        dg = nx.Graph()
        queue = deque()
        crimes = [Vertex(row["Case"], row["Type"], row["Longitude"], row["Latitude"]) for index, row in df.iterrows()]
        if len(crimes) == 0:
            print("none found")
            return
        copy = [vertex for vertex in crimes]
        if src is None:
            queue.append(crimes[0])
        else:
            queue.append(list(filter(lambda x: x.id == src, crimes)))

        visited = []
        for crime in crimes:
            dg.add_node(crime.id)
        while len(queue) > 0:
            current = queue.popleft()
            crimes.remove(current)
            for crime in crimes:
                if crime.distance_to(current) < factor and crime not in visited:
                    dg.add_edge(current.id, crime.id, weight=crime.distance_to(current))
                    queue.append(crime)
                    visited.append(crime)
            visited.append(current)
            if len(queue) == 0 and len(crimes) > 0:
                queue.append(crimes[0])


        pos = {copy[i].id: self.base_map(copy[i].lon, copy[i].lat) for i in range(len(copy))}

        if color is None:
            color = "red"
        nx.draw_networkx(dg, pos=pos, node_size=5, with_labels=False, ax=self.ax, node_color=color)

        plt.show()

    def gen_colorbar(self, colors, color_map, labels=None, **kwargs):
        """Create colour scale bar on map
        
        Args:
            colors: colours of map
            color_map: chloropleth map
            labels: label of map, default none
            kwargs: arguments for colourbar
        Returns:
            a colorbar
        """
        color_map = self.split_colormap(color_map, colors)
        mappable = cm.ScalarMappable(cmap=color_map)
        mappable.set_array([])
        mappable.set_clim(-0.5, colors + 0.5)
        colorbar = plt.colorbar(mappable, **kwargs)
        colorbar.set_ticks(np.linspace(0, colors, colors))
        colorbar.set_ticklabels(range(colors))
        if labels:
            colorbar.set_ticklabels(labels)
        return colorbar

    def split_colormap(self, colormap, n):
        """splits map by colour
        
        Args:
            colormap: chloropleth map
            n: colours
        Returns:
            portion of split map
        """
        if type(colormap) == str:
            colormap = cm.get_cmap(colormap)
        colors = np.concatenate((np.linspace(0, 1., n), (0., 0., 0., 0.)))
        rgb_alpha = colormap(colors)
        indices = np.linspace(0, 1., n + 1)
        color_dict = {}
        for color, key in enumerate(('red', 'green', 'blue')):
            color_dict[key] = [(indices[i], rgb_alpha[i - 1, color], rgb_alpha[i, color]) for i in range(n + 1)]
        return LinearSegmentedColormap(colormap.name + "_%d" % n, color_dict, 1024)
Example #17
0
Data file tweets.dat contains binary lon/lat data only

Author: Kelsey Jordahl, Enthought
Scipy 2013 geospatial tutorial
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib import cm

N = 405146
west, south, east, north = -74.26, 40.50, -73.70, 40.92
#west, south, east, north = -74.03, 40.69, -73.93, 40.82
cwd = os.path.dirname(os.path.abspath(__file__))
datadir = os.path.join(os.path.split(cwd)[0], 'data')
tweetfile = os.path.join(datadir, 'tweets.dat')
ll = np.dtype([('lon', np.float32), ('lat', np.float32)])
tweets = np.memmap(tweetfile, dtype=ll, mode='r', shape=(N,))

fig = plt.figure()
ax = fig.add_subplot(111)
m = Basemap(projection='merc', llcrnrlat=south, urcrnrlat=north,
            llcrnrlon=west, urcrnrlon=east, lat_ts=south, resolution='i')
x, y = m(tweets['lon'], tweets['lat'])
m.hexbin(x, y, gridsize=400,
         bins='log', cmap=cm.YlOrRd_r)
plt.title("Twitter Heatmap")
plt.savefig('tweets.png', dpi=300, bbox_inches='tight')
plt.show()
figwidth = 14
fig = plt.figure(figsize=(figwidth, figwidth*h/w))
ax = fig.add_subplot(111, axisbg='w', frame_on=False)

# draw neighborhood patches from polygons
df_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(
    x, fc='#555555', ec='#555555', lw=1, alpha=1, zorder=0))
# plot neighborhoods by adding the PatchCollection to the axes instance
ax.add_collection(PatchCollection(df_map['patches'].values, match_original=True))

# the mincnt argument only shows cells with a value >= 1
# The number of hexbins you want in the x-direction
numhexbins = 50
hx = m.hexbin(
    np.array([geom.x for geom in city_points]),
    np.array([geom.y for geom in city_points]),
    gridsize=(numhexbins, int(numhexbins*h/w)), #critical to get regular hexagon, must stretch to map dimensions
    bins='log', mincnt=1, edgecolor='none', alpha=1.,
    cmap=plt.get_cmap('Blues'))

# Draw the patches again, but this time just their borders (to achieve borders over the hexbins)
df_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(
    x, fc='none', ec='#FFFF99', lw=1, alpha=1, zorder=1))
ax.add_collection(PatchCollection(df_map['patches'].values, match_original=True))

# Draw a map scale
m.drawmapscale(coords[0] + 0.05, coords[1] - 0.01,
    coords[0], coords[1], 4.,
    units='mi', barstyle='fancy', labelstyle='simple',
    fillcolor1='w', fillcolor2='#555555', fontcolor='#555555',
    zorder=5)
points_x = np.array([x['X'] for i,x in merge.iterrows()])
points_y = np.array([x['Y'] for i,x in merge.iterrows()])
c = np.array([x['internet'] for i,x in merge.iterrows()])

# Trentino's boundingbox
a = (45.6730682227551, 10.4521594968354)
b = (46.5327699992773, 11.9627133503828)

# Trentino shapefile
# http://dati.trentino.it/dataset/limite-comprensoriale-027140/resource/ff1f1687-3f8f-427e-84d9-cf40c8b9b98a
m = Basemap(lat_0 = (a[0]+b[0])/2, lon_0 = (a[1]+b[1])/2, epsg=4326, llcrnrlon=a[1],llcrnrlat=a[0],urcrnrlon=b[1],urcrnrlat=b[0],)
m.readshapefile('nature/amm','Trentino_shapefile', color='0.35')

cmap = LinearSegmentedColormap.from_list("skil", sns.color_palette("RdBu_r", 7)[1:])
plt.register_cmap(cmap=cmap)
m.hexbin(points_x, points_y, cmap="skil", gridsize=50, C=c, bins='log', mincnt=1)
sns.despine(left=True, bottom=True)
plt.savefig('map.pdf', format='pdf', dpi=330, bbox_inches='tight')


# Import the dataset - social pulse, obtained from the geojson
social_df = pd.read_csv('nature/result2.csv', sep=',', encoding="utf-8-sig", parse_dates=['created'])
points_x = np.array([x['geomPoint.geom/coordinates/0'] for i,x in social_df.iterrows()])
points_y = np.array([x['geomPoint.geom/coordinates/1'] for i,x in social_df.iterrows()])

m = Basemap(lat_0 = (a[0]+b[0])/2, lon_0 = (a[1]+b[1])/2, epsg=4326, llcrnrlon=a[1], llcrnrlat=a[0], urcrnrlon=b[1], urcrnrlat=b[0],)
m.readshapefile('nature/amm', 'Trentino_shapefile', color='0.35')

m.hexbin(points_x, points_y, cmap="skil", gridsize=50, bins='log', mincnt=1)
sns.despine(left=True, bottom=True)
plt.savefig('map_social.pdf', format='pdf', dpi=330,bbox_inches='tight')
Example #20
0
for info, lightning in zip(map.lightnings_info, map.lightnings):
    x.append(lightning[0])
    y.append(lightning[1])
    
    if float(info['amplitude']) < 0:
        c.append(-1 * float(info['amplitude']))
    else:
        c.append(float(info['amplitude']))
    
plt.figure(0)

map.drawcoastlines()
map.readshapefile('../sample_files/comarques', 'comarques')

map.hexbin(array(x), array(y))

map.colorbar(location='bottom')



plt.figure(1)

map.drawcoastlines()
map.readshapefile('../sample_files/comarques', 'comarques')

map.hexbin(array(x), array(y), gridsize=20, mincnt=1, cmap='summer', bins='log')

map.colorbar(location='bottom', format='%.1f', label='log(# lightnings)')

	x = np.array(xlat + txlat)
	y = np.array(xlon + txlon)


	gridsize=2000

	m  = Basemap(lon_0=-98.0, projection='robin')

	xpt, ypt = m(y, x)

	print(type(predictions))
	print(type(Y))

	totalLabels = Y + list(predictions)
	
	m.hexbin(xpt, ypt, C=totalLabels, gridsize = gridsize)
	#m.scatter(xpt, ypt, c=predictions)
	m.readshapefile('./tl_2013_40_prisecroads', 'Roads')
	
	m.drawcoastlines()
	m.drawparallels(np.arange(0,81,20))
	m.drawmeridians(np.arange(-180,181,60))
	m.colorbar() # draw colorbar
	plt.title('Donors')
	
	#m.hexbin(x1, y1, C=predictions, gridsize=gridsize, cmap=plt.cm.jet)
	#m.hexbin(x, y, gridsize=20, cmap=plt.cm.jet)
	#plt.axis([min(x), max(x), min(y), max(y)])
	#m.colorbar()

	plt.show()