Exemplo n.º 1
0
def plot_linestring(geometry, speed_color=None, config=None):
    if (type(geometry) == LineString):
        geometry = gpd.GeoSeries(geometry)
    # set initial coords as first point of first linestring
    geometry_ = geometry.geometry[0]
    initial_coords = [geometry_.xy[1][0], geometry_.xy[0][0]]

    map_ = folium.Map(initial_coords, zoom_start=14)

    traces_json = json.loads(geometry.buffer(.00001).to_json())
    if (speed_color is not None):
        if (np.mean(speed_color) > 1):  # if absolute speeds
            red_speed, yellow_speed, blue_speed = 0, 25, 40
            cmap_caption = 'Speed Km/h'
        else:  # if relative speed
            red_speed, yellow_speed, blue_speed = 0, .4, .8
            cmap_caption = 'Relative Speed to Maximum %'

        speed_cm = LinearColormap(
            ['red', 'yellow', 'blue'],
            vmin=red_speed,
            vmax=blue_speed + (blue_speed * .2),  # 20% maxspeed
            index=[red_speed, yellow_speed, blue_speed])
        speed_cm.caption = cmap_caption

        for elem, speed in zip(traces_json['features'], speed_color):
            elem['properties']['style'] = {}
            elem['properties']['style']['color'] = speed_cm(speed)
            elem['properties']['style']['fillOpacity'] = 1

        map_.add_child(speed_cm)

    traces = folium.features.GeoJson(traces_json)
    map_.add_child(traces)
    return map_
                    'style': {
                        'color': row['Color']
                    }
                }
            }
            features.append(feature)
            if row["id"] in ["DNK", "FRA", "ITA", "GBR", "GRC"]:
                for geometry in compl.get(row["id"]).get("geometries"):
                    feature_new = dict(feature)
                    feature_new["geometry"] = geometry
                    features.append(feature_new)
    new_map = folium.Map([50.736455, 17.666], zoom_start=4.5)

    TimestampedGeoJson({
        'type': 'FeatureCollection',
        'features': features
    },
                       period='P1M',
                       duration='P1M',
                       add_last_point=True,
                       auto_play=False,
                       loop=False,
                       max_speed=1,
                       loop_button=True,
                       date_options='YYYY/MM',
                       time_slider_drag_update=True).add_to(new_map)
    colormap = LinearColormap(color_scale, vmin=0, vmax=bin_edges[-1])
    colormap.caption = "Monthly average " + pollutant + " (in µg/m3)"
    colormap.add_to(new_map)
    new_map.save("../maps/avg_" + pollutant + ".html")
Exemplo n.º 3
0
def create_state_count_choropleth(df, designation):
    '''
    This function counts the number of parks per state and stores the
    result in a dataframe. Then it creates a linear color map using the
    range of parks per state. The function then reads in a GeoJSON file
    of the United States and merges this with the parks per state
    dataframe. These objects are then used to create a choropleth map
    of the United States with state color based on the number of parks
    in that state. If there are no parks in a state, it will be gray.

    Parameters
    ----------
    df : Pandas DataFrame
      DataFrame of all parks to add to the map.

    designation : str
      Designation of parks in the dataframe.

    Returns
    -------
    map : Folium map object
      Folium map with choropleth color added.
    '''

    # Create a two-column dataframe of state and a count of the number
    # of parks in that state.
    state_list = df['states'].apply(lambda x: x.split(','))
    state_list = reduce(operator.add, state_list)
    parks_per_state = (pd.DataFrame.from_dict(Counter(state_list),
                                              orient='index').reset_index())
    parks_per_state = (parks_per_state.rename(columns={
        'index': 'state',
        0: 'park_count'
    }))

    # Create the color map.
    color_scale = LinearColormap(['yellow', 'green', 'blue'],
                                 vmin=parks_per_state['park_count'].min(),
                                 vmax=parks_per_state['park_count'].max())
    color_scale.caption = (
        "Number of parks per state ({})".format(designation))

    # Create a dataframe from the json file using GeoPandas.
    df_geo = gpd.read_file('_reference_data/us-states.json')
    df_geo = df_geo.merge(parks_per_state,
                          left_on='id',
                          right_on='state',
                          how='left').fillna(0)

    # Find the center of the data and create an empty map.
    centroid = df_geo.geometry.centroid
    map = folium.Map(location=[centroid.y.mean(),
                               centroid.x.mean()],
                     zoom_start=3)

    # Color each state based on the number of parks in it.
    folium.GeoJson(
        data=df_geo[['geometry', 'name', 'state', 'park_count']],
        name='United States of America',
        style_function=lambda x: {
            'fillColor': get_state_color(x, parks_per_state, color_scale),
            'fillOpacity': 0.7,
            'color': 'black',
            'line_opacity': 0.5,
            'weight': 0.5
        },
        tooltip=folium.features.GeoJsonTooltip(fields=[
            'name',
            'park_count',
        ],
                                               aliases=["State", "# of parks"
                                                        ])).add_to(map)

    # Add color scale legend.
    map.add_child(color_scale)

    # Save choropleth to file.
    map.save(set_filename('choropleth_map', 'html', designation))

    return map