Beispiel #1
0
def print_city_districts(city, opacity=None):
    """
    It prints all the districts of a city by looking at its geojson file.

    Parameters
    ----------
    city : string
        Name of the city whose districts we want to display.
    opacity : float
        It defines the opacity of the district layers. It supports a value in
        the range of [0,1]

    Returns
    -------
    my_map : gmaps object
        This object will be used to plot the map and all activities locations
        in a Jupyter Notebook.
    """
    my_map = gmaps.figure()
    with open('geojson/{}.geojson'.format(city), 'r') as f:
        districts_geometry = json.load(f)
    my_map.add_layer(
        gmaps.geojson_layer(districts_geometry,
                            stroke_color='black',
                            fill_opacity=(opacity or co.LAYER_TRANSPARENCY)))
    return my_map
Beispiel #2
0
def make_the_base_map():
    # set constants
    main_path = 'data'
    global api_key
    api_key = open(main_path + '/config.py', 'r')
    api_key = api_key.read().replace('api_key = ',
            '').replace('“','').replace('”','')
    gmaps.configure(api_key=api_key) # Your Google API key

    # get information
    df = pd.read_csv(main_path + '/nyc_blk_map_with_vals_for_front_end_FILTERED.csv')
    with open(main_path + '/BoroughBoundaries.geojson') as f:
        geometry = json.load(f)
    global nbhd_map
    nbhd_map = gpd.read_file(main_path + '/nyc_nbhd_map.shp')

    # Control the display
    global new_york_coordinates
    new_york_coordinates = (40.75, -73.9)
    heatmap_gradient = [
        (250, 185, 123, 0),
        'yellow',
        (249, 127, 77, 1),
        'red',
    ]

    # define layers
    global geojson_layer
    global heatmap_layer
    geojson_layer = gmaps.geojson_layer(geometry, fill_color=(0,0,0,0), 
            fill_opacity=1, stroke_weight=0.5)
    heatmap_layer = gmaps.heatmap_layer(df[['latitude', 'longitude']], 
            weights=df['magnitude'], max_intensity=10, 
            point_radius=0.00075, opacity=1, gradient=heatmap_gradient,
            dissipating=False)
Beispiel #3
0
    def aois_on_gmaps_html(self):
        aois = gpd.read_file("static/aois.geojson")
        aois = aois.to_crs({'init': 'epsg:4326'})

        figure_layout = {
            'width': '100%',
            'height': '50em',
        }

        fig = gmaps.figure(center=[47.372, 8.541],
                           zoom_level=16,
                           layout=figure_layout)
        geojson_layer = gmaps.geojson_layer(geojson.loads(aois.to_json()),
                                            fill_opacity=0.01)
        fig.add_layer(geojson_layer)
        fig

        embed_minimal_html('/tmp/export.html', views=[fig])
        with open('/tmp/export.html') as f:
            return f.read()
Beispiel #4
0
def load_districts_layer(city,
                         colorscheme,
                         counter_data=None,
                         opacity=None,
                         invert=False,
                         per_capita=False,
                         verbose=False):
    """
    Loads and computes for a given city a layer corresponding to the
    district's population density

    Parameters
    ----------
    city : string
        Name of the city to which the csv belongs
    colorscheme : string
        It defines the colorscheme that will be used in the painting of the
        districts. It supports: 'Greys','viridis','inferno and 'plasma'.
    counter_data : dictionary
        If supplied, it will help to paint the districts according to the
        number of activities that each one has.
    opacity : float
        It defines the opacity of the district layers. It supports a value in
        the range of [0,1]
    invert : boolean
        If true, it inverts the colors of the colorscheme.
    per_capita : boolean
        If true, and if counter_data is provided, it will paint districts
        according to the (Number of activites in a district) / (Population in
        this district) ratio.
    verbose : boolean
        If true, it will display the numeric results of the total number of
        events that were found in each district.

    Returns
    -------
    gmaps geojson layer for mapping
    """
    with open('geojson/{}.geojson'.format(city), 'r') as f:
        districts_geometry = json.load(f)

    population = distr.read_district_csv(city, "Population")

    if counter_data is None:
        density = distr.read_district_csv(city, "Density")

    else:
        if per_capita:
            density = {}
            for district_name, events_number in counter_data.items():
                if district_name == "Not Located":
                    continue
                density[district_name] = events_number / \
                    population[district_name]
        else:
            density = {}
            for district_name, events_number in counter_data.items():
                if district_name == "Not Located":
                    continue
                density[district_name] = events_number
                # density = counter_data

    colors = []
    district_colors = distr.calculate_color(density,
                                            colorscheme,
                                            invert=invert)

    for elem in districts_geometry['features']:
        current_name = elem['properties'].get('name')
        colors.append(district_colors[current_name])

    # set opacity if no argument given
    if opacity is None:
        opacity = co.LAYER_TRANSPARENCY

    if verbose:
        for district in districts_geometry['features']:
            district_name = district['properties']['name']
            print("District: {}  |  Number of events: {}".format(
                district_name, counter_data[district_name]) +
                  "  |  Population: {}".format(population[district_name]))

    return gmaps.geojson_layer(districts_geometry,
                               fill_color=colors,
                               stroke_color=colors,
                               fill_opacity=opacity)
Beispiel #5
0
import gmaps
import json
import requests
countries_string = requests.get(
    "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json"
).content
countries = json.loads(countries_string)
gmaps.configure(api_key="AI...")
fig = gmaps.figure()
geojson = gmaps.geojson_layer(countries)
fig.add_layer(geojson)
fig
Beispiel #6
0
heatmap_fig = gmaps.figure()
heatmap_layer = gmaps.heatmap_layer(locations, weights=weights)
heatmap_fig.add_layer(heatmap_layer)
heatmap_fig

# %%
heatmap_layer.max_intensity = 100
heatmap_layer.point_radius = 10

# %%
import gmaps.geojson_geometries
countries_geojson = gmaps.geojson_geometries.load_geometry('countries')

fig = gmaps.figure()

gini_layer = gmaps.geojson_layer(countries_geojson)
fig.add_layer(gini_layer)
fig

# %%
import pandas as pd
import vincent
import random
vincent.core.initialize_notebook()

#Dicts of iterables
cat_1 = ['y1', 'y2', 'y3', 'y4']
index_1 = range(0, 21, 1)
multi_iter1 = {'index': index_1}
for cat in cat_1:
    multi_iter1[cat] = [random.randint(10, 100) for x in index_1]
Beispiel #7
0
def plot_places_on_gmaps(polygon_geojsons=None,
                         circle_geojsons=None,
                         heatmaps=None,
                         points=None):
    """
    :param polygon_geojsons: list of polygon_geojsons for geojson_layer gmaps
    objects
    :param circle_geojsons: list of circle_geojsons for geojson_layer gmaps
    objects
    :param heatmaps: list of 2d numpy array of points of shape (num_points, 2)
    (decimal lat/lon degrees) for heatmap_layer gmaps objects
    :param points: 2d numpy array of points of shape (num_points, 2)
    (decimal lat/lon degrees), for a symbol_layer gmaps object
    :return: the gmaps.figure() object, which is a Google Maps interactive map

    gmaps documentation: http://jupyter-gmaps.readthedocs.io/en/latest/gmaps.html

    NOTE: when trying to create the polygon and circle geojsons, make sure 
    there are more than 3 points being provided, otherwise they won't 
    appear. In this case, should put them in the 'points' category.

    NOTE: the heatmap colour levels are independent from one heatmap object to 
    another

    NOTE: when showing map in jupyter notebook, the widget's "save" button 
    doesn't work (saves a blank image)

    WARNING: should create a Neura Google Maps Javascript API key. The one
    it is currently using is hard-coded in this package.
    """
    fig = gmaps.figure()

    if polygon_geojsons is not None:
        for geojson in polygon_geojsons:
            if geojson is not None:
                try:
                    geojson_layer = gmaps.geojson_layer(geojson,
                                                        fill_color=['red'],
                                                        stroke_color=['red'],
                                                        fill_opacity=0.1)
                    fig.add_layer(geojson_layer)
                except:
                    warnings.warn("failed to add polygon")
                    continue

    if circle_geojsons is not None:
        for geojson in circle_geojsons:
            if geojson is not None:
                try:
                    geojson_layer = gmaps.geojson_layer(geojson,
                                                        fill_opacity=0.1)
                    fig.add_layer(geojson_layer)
                except:
                    warnings.warn("failed to add circle")
                    continue

    if heatmaps is not None:
        for heatmap in heatmaps:
            try:
                heatmap_layer = gmaps.heatmap_layer(heatmap)
                heatmap_layer.point_radius = 15
                heatmap_layer.gradient = [(255, 0, 0, 0), (255, 0, 0, 0.7),
                                          (255, 0, 0, 0.99)]
                fig.add_layer(heatmap_layer)
            except:
                warnings.warn("failed to add heatmap")
                continue

    if points is not None:
        try:
            symbol_layer = gmaps.symbol_layer(
                points,
                fill_color="rgba(0, 0, 255, 0.5)",
                stroke_color="rgba(0, 0, 255, 0.5)")
            fig.add_layer(symbol_layer)
        except:
            warnings.warn("failed to add points")

    return fig
Beispiel #8
0
# Reorder Columns for Readability
finaldf = finaldf[[
    "State", "Population Change", "Population Score", "Home Buying Power",
    "Home Buying Score", "Education Change", "Education Score",
    "Unemployment Change", "Unemployment Score"
]]
finaldf["Composite Score"] = finaldf["Population Score"] + finaldf[
    "Education Score"] + finaldf["Unemployment Score"] + finaldf[
        "Home Buying Score"]
finaldf["Composite Rank"] = finaldf["Composite Score"].rank(ascending=False)

# Begin Building Gmaps states layer
states_geojson = gmaps.geojson_geometries.load_geometry('us-states')
fig = gmaps.figure()
state_layer = gmaps.geojson_layer(states_geojson)
fig.add_layer(state_layer)

# Transform dataframe into dictionary in order to allow gmaps to iterate through
finaldict = finaldf[["State", "Unemployment Change"]]
finaldict.set_index("State", inplace=True)
finaldict2 = finaldict.to_dict()

# Scale the values
# Note: When negative values are better, use the inverse function for min/max
min_unemployment = max(finaldf["Unemployment Change"])
max_unemployment = min(finaldf["Unemployment Change"])
unemployment_range = min_unemployment - max_unemployment


# Create a function to transform the values into a color