Exemple #1
0
class Cell(object):
    """ """

    offstyle = {"fill_opacity": 0, "color": "white", "weight": 0.75}
    onstyle = {"fill_opacity": 0.4, "color": "lightgreen", "weight": 1}

    def __init__(self, feat):
        """Inits with id,lat,lon; makes request string, map point."""

        self.feat = feat
        self.shape = shape(feat["geometry"])

        self.prop = feat["properties"]
        self.feat["properties"]["style"] = {
            "fill_opacity": 0.1,
            "opacity": 0.1,
            "color": "white",
            "weight": 0.75
        }
        self.id = self.prop["grid_id"]
        self.level = self.prop["grid_level"]

        self.layer = GeoJSON(data=self.feat,
                             hover_style={
                                 "weight": 1,
                                 "color": "white",
                                 "fillColor": "white",
                                 "fillOpacity": 0.3
                             })
        self.layer.on_click(self.toggle)
        self.on = False

    def toggle(self, **kwargs):
        """Routine for when a cell is toggled on."""
        self.on = False if self.on else True
def show_map(selected_stats, year): 
    control = WidgetControl(widget=districtbox, position='topright', min_width = 250, max_width=500)

    # load selected stats into choro_data_all
    choro_data_all, unit = choro_data_complete[selected_stats], units[selected_stats]
    # for geo plot extract chosen year and assign to choro_data
    choro_data = choro_data_all[choro_data_all['year']==year]
    choro_data = dict(choro_data.drop(columns=['year', 'name']).to_dict('split')['data'])
    
    # initialize bar chart with Frankfurt vs Offenbach
    update_figure('06412', selected_stats, choro_data_all, year)
    update_figure('06413', selected_stats, choro_data_all, year)

    # initialize districtbox
    loading_name, loading_values = id_to_name['06413'], choro_data['06413']
    districtbox.value = f'<center><p><b>{loading_name}</b>:</p> {loading_values:g} {unit} {norm_unit}</center>'
    
    # set y-axis label
    fig.update_layout(yaxis_title=f'{stat_dict[selected_stats]} [{unit} {norm_unit}]', yaxis={'range':[0,max(choro_data_all[selected_stats])]})
    

    # define chropleth layer for basic geo plotting
    layer = Choropleth(geo_data=geo_data,choro_data=choro_data,colormap=cm,
                       style={'fillOpacity': 0.65, 'dashArray': '0, 0', 'weight':1})
    
    # define GeoJSON layer for click and hover event interactions
    geo_json = GeoJSON(data=geo_data,
                       style={'opacity': 0, 'dashArray': '9', 'fillOpacity': .0, 'weight': 1},
                       hover_style={'color': 'blue', 'dashArray': '0', 'fillOpacity': 0.7})

    # on hover, the districtbox is updated to show properties of the hovered district
    def update_districtbox(feature,  **kwargs):
        feature['value'] = choro_data[feature['id']]
        districtbox.value = f'<center><p><b>{id_to_name[feature["id"]]}</b>:</p> {feature["value"]:g} {unit} {norm_unit}</center>'

    # this function is called upon a click events and triggers figure update with the arguments passed from the map
    def update_fig_on_click(feature, **kwags):
        update_figure(feature['id'], selected_stats, choro_data_all, year)
    geo_json.on_hover(update_districtbox)
    geo_json.on_click(update_fig_on_click)

    # add layers and controls; set layout parameters
    m = Map(basemap=basemaps.OpenStreetMap.Mapnik, center=(50.5,9), zoom=8)
    m.add_layer(layer)
    m.add_layer(geo_json)
    m.add_control(control)
    m.layout.width = '40%'
    m.layout.height = '700px'

    # custom made legend using min/max normalization
    min_value, max_value = min(choro_data.values()), max(choro_data.values())
    legend = LegendControl(
          {f"{min_value:g} {unit}  {norm_unit}": cm(0), #hier
          f"{min_value+0.5*(max_value-min_value):g} {unit}  {norm_unit}": cm(.5),
          f"{max_value:g} {unit}  {norm_unit}": cm(1)},
          name= f"{stat_dict[selected_stats]} ({year})", position="bottomleft")
    m.add_control(legend)
    return HBox([m, fig], layout=Layout(width='85%'))

    
Exemple #3
0
def map_shapefile(gdf, colormap=mpl.cm.YlOrRd, weight=2, default_zoom=13):
    def n_colors(n, colormap=colormap):
        data = np.linspace(0.0, 1.0, n)
        c = [mpl.colors.rgb2hex(d[0:3]) for d in colormap(data)]
        return c

    def data_to_colors(data, colormap=colormap):
        c = [
            mpl.colors.rgb2hex(d[0:3])
            for d in colormap(mpl.colors.Normalize()(data))
        ]
        return c

    def click_handler(event=None,
                      id=None,
                      properties=None,
                      type=None,
                      coordinates=None):
        try:
            datasetID = properties['time']
            print(datasetID)
        except:
            pass

    # Convert to WGS 84 and geojson format
    gdf_wgs84 = gdf.to_crs(epsg=4326)
    data = gdf_wgs84.__geo_interface__

    # For each feature in dataset, append colour values
    n_features = len(data['features'])
    colors = n_colors(n_features)

    for feature, color in zip(data['features'], colors):
        feature['properties']['style'] = {
            'color': color,
            'weight': weight,
            'fillColor': color,
            'fillOpacity': 1.0
        }

    # Get centroid to focus map on
    lon, lat = gdf_wgs84.unary_union.centroid.coords.xy

    # Plot map and add geojson layers
    m = Map(center=(lat[0], lon[0]),
            zoom=default_zoom,
            basemap=basemaps.Esri.WorldImagery,
            layout=dict(width='800px', height='600px'))
    feature_layer = GeoJSON(data=data)
    feature_layer.on_click(click_handler)
    m.add_layer(feature_layer)

    return m