def render(self): #print("Avant de descendre dans le decorateur etc") geo_file,legend_file = self.get_step(variable= self.variable) #print("On en revient ici") geojson_layer = ipyl.GeoJSON(data=geo_file,hover_style={"opacity":1},name="AROME") if hasattr(self,"geojson_layer"): if self.geojson_layer in self.m.layers: self.m.substitute_layer(self.geojson_layer,geojson_layer) else: #print("par ici?") self.m.add_layer(geojson_layer) else: self.m.add_layer(geojson_layer) self.geojson_layer = geojson_layer self.geojson_layer.on_hover(self.update_html) legend_file.seek(0) self.legend.value =legend_file.read() chor_layer = ipyl.Choropleth(geo_data=self.region_geo, choro_data=self.da_aggregated.isel(step=self.step).to_pandas().to_dict(), name="zonage sur temps sensible (WME)", value_min = self.vmin, value_max = self.vmax, colormap=linear.RdBu_03) if hasattr(self,"chor_layer"): if self.chor_layer in self.m.layers: #print("on passe la") self.m.substitute_layer(self.chor_layer,chor_layer) else: #print("ici") self.m.add_layer(chor_layer) else: #print('ou la') self.m.add_layer(chor_layer) self.chor_layer = chor_layer self.chor_layer.on_hover(self.update_chor_html) chor_layer2 = ipyl.Choropleth(geo_data=self.region_geo2, choro_data=self.toto, name="zonage sur homogeneous temps sensible criterion ("+self.distance_choice+")", value_min = self.vmin, value_max = self.vmax, colormap=linear.RdBu_07) if hasattr(self,"chor_layer2"): if self.chor_layer2 in self.m.layers: #print("et par la") self.m.substitute_layer(self.chor_layer2,chor_layer2) else: #print('et ici') self.m.add_layer(chor_layer2) else: #print('et ou la') self.m.add_layer(chor_layer2) self.chor_layer2 = chor_layer2 self.chor_layer2.on_hover(self.update_chor_html2)
def update_homo_area(self): # On change les donnes de Gab if self.distance_choice in ["compas","compas_asym"]: variable = "WME" else: variable = "W1" (code,hexc,_) = geo_gv.get_cmap_info(variable) cmap = cm.StepColormap(hexc.values,index=np.asarray(code).astype(float),vmin=code[0],vmax=code[-1]+1) chor_layer2 = ipyl.Choropleth(geo_data=self.region_geo2, choro_data=self.homo_zone, name="zonage sur homogeneous temps sensible criterion ("+self.distance_choice+")", value_min = float(code[0]), value_max = float(code[-1]+1), colormap = cmap, border_color="red", style={'fillOpacity': 0.8, 'dashArray': '5, 5',"opacity":0.5}, hover_style={"opacity":1,"color":"black","weight":4}) chor_layer2.value_min = float(code[0]) chor_layer2.value_max = code[-1]*1.0 if hasattr(self,"chor_layer2"): if self.chor_layer2 in self.m.layers: #print("et par la") self.m.substitute_layer(self.chor_layer2,chor_layer2) else: #print('et ici') self.m.add_layer(chor_layer2) else: #print('et ou la') self.m.add_layer(chor_layer2) self.chor_layer2 = chor_layer2 self.chor_layer2.on_hover(self.update_chor_html2)
def create_choropleth_layer(self, key): """add choropleth layer to map. Args: key (str): A selected value from tablemap's layer selection drop down menu. """ # vmax_val = max(self.bldg_data_df[key]) vmax_val = 1 temp_id = list(range(len(self.inventory_df['guid']))) temp_id = [str(i) for i in temp_id] choro_data = dict(zip(temp_id, self.inventory_df[key])) try: self.map.remove_layer(self.layer) print("removed previous layer") except Exception: print("there is no existing layer") pass self.layer = ipylft.Choropleth(geo_data=self.inventory_json, choro_data=choro_data, colormap=linear.YlOrRd_04, value_min=0, value_max=vmax_val, border_color='black', style={'fillOpacity': 0.8}, name='dataset map') self.map.add_layer(self.layer) print('Done loading layer.')
def build_us_cntymap(dataframe, colname): global geojson_cnty, this_cnty_colname, cnty_overlay, county_data_dict global cnty_layer, cnty_legend, cnty_control global MapsVDict, geojson_cnty, mapcenter, mapzoom, loc_dict # This function builds a US Choropleth Map (but doesn't display it) for the county-level # data provided. # Load data needed to build either kind of map build_us_genericmap() # Build location dictionary if doesn't yet exist try: loc_dict except NameError: loc_dict = BuildLocationDict(dataframe) # ipyleaflet requires a dictionary for the choro_data field/the variable to be visualized, # so convert the Pandas data series into the appropriate dictionary setting keys to postal # codes used in geojson_states county_data_dict = get_cnty_dict(dataframe, colname) # Determine range of values for colormap, then define colormap (need to also pass # max/min values to Choropleth builder or they are ignored). Set up legend dictionary # to show this range. (minval, maxval) = set_cm_limits(county_data_dict) cmap = BuildColormap(minval, maxval) legendDict = BuildLegendDict(minval, maxval, cmap) # Creating the map cnty_map = lf.Map(center=mapcenter, zoom=mapzoom) # Draw a functional counties layer cnty_layer = lf.Choropleth( geo_data=geojson_cnty, choro_data=scrub(county_data_dict), key_on='id', # Below here is some formatting/coloring from the documentation colormap=cmap, value_min=minval, value_max=maxval, border_color=map_border_color, hover_style=map_hover_style, style=map_style) cnty_map.add_layer(cnty_layer) # Display a legend cnty_legend = lf.LegendControl(legendDict, name="Legend", position="bottomleft") cnty_map.add_control(cnty_legend) # Display data in overlay this_cnty_colname = colname cnty_overlay = widgets.HTML("Hover over Location for Details") cnty_control = lf.WidgetControl(widget=cnty_overlay, position='topright') cnty_map.add_control(cnty_control) cnty_layer.on_hover(update_cnty_overlay) return (cnty_map, cnty_legend, cnty_overlay)
def create_choropleth_layer(self, key): # vmax_val = max(self.bldg_data_df[key]) vmax_val = 1 temp_id = list(range(len(self.bldg_data_df['guid']))) temp_id = [str(i) for i in temp_id] choro_data = dict(zip(temp_id, self.bldg_data_df[key])) layer = ipylft.Choropleth(geo_data=self.bldg_data_json, choro_data=choro_data, colormap=linear.YlOrRd_04, value_min=0, value_max=vmax_val, border_color='black', style={'fillOpacity': 0.8}, name='Tax-Lots') self.m.add_layer(layer) # self.m print('done')
def update_us_cntymap(dataframe, colname, thismap, thislegend, thisoverlay): global geojson_cnty, this_cnty_colname, county_data_dict, cnty_overlay, loc_dict # This function updates an existing US County-level Choropleth map # Build location dictionary if doesn't yet exist try: loc_dict except NameError: loc_dict = BuildLocationDict(dataframe) # Load the new data and determine the new colormap limits county_data_dict = get_cnty_dict(dataframe, colname) (minval, maxval) = set_cm_limits(county_data_dict) cmap = BuildColormap(minval, maxval) legendDict = BuildLegendDict(minval, maxval, cmap) # Assign updated legend dictionary thislegend.legends = legendDict # Draw a functional counties layer cnty_layer_update = lf.Choropleth( geo_data=geojson_cnty, choro_data=scrub(county_data_dict), key_on='id', # Below here is some formatting/coloring from the documentation colormap=cmap, value_min=minval, value_max=maxval, border_color=map_border_color, hover_style=map_hover_style, style=map_style) # Replace existing Choropleth layer (which is always the second layer with new layer cnty_layer = thismap.layers[1] thismap.substitute_layer(cnty_layer, cnty_layer_update) cnty_layer = cnty_layer_update # Update column name used by state overlay to look up values this_cnty_colname = colname thisoverlay.value = "Hover over Location for Details" cnty_overlay = thisoverlay cnty_layer_update.on_hover(update_cnty_overlay) return
def render(self): # On ajoute le choropleth chor_layer = ipyl.Choropleth(geo_data=self.region_geo, choro_data=self.da_aggregated.isel(step=self.step).to_pandas().to_dict(), name="regional_mean", value_min = self.vmin, value_max = self.vmax, colormap=linear.RdBu_03) if hasattr(self,"chor_layer"): if self.chor_layer in self.m.layers: self.m.substitute_layer(self.chor_layer,chor_layer) else: self.m.add_layer(chor_layer) else: self.m.add_layer(chor_layer) self.chor_layer = chor_layer self.chor_layer.on_hover(self.update_chor_html) # On ajoute l'interactivité sur click self.chor_layer.on_click(self.hist_html)
def update_us_statesmap(dataframe, colname, thismap, thislegend, thisoverlay): global geojson_states, this_state_colname, state_data_dict, state_overlay # This function updates an existing US State-level Choropleth map # Load the new data and determine the new colormap limits and set up legend dictionary # to show this range. state_data_dict = get_state_dict(dataframe, colname) (minval, maxval) = set_cm_limits(state_data_dict) cmap = BuildColormap(minval, maxval) legendDict = BuildLegendDict(minval, maxval, cmap) # Assign updated legend dictionary thislegend.legends = legendDict # Draw a functional states layer state_layer_update = lf.Choropleth( geo_data=geojson_states, choro_data=scrub(state_data_dict), key_on='id', # Below here is some formatting/coloring from the documentation colormap=cmap, value_min=minval, value_max=maxval, border_color=map_border_color, hover_style=map_hover_style, style=map_style) # Replace existing Choropleth layer (which is always the second layer with new layer state_layer = thismap.layers[1] thismap.substitute_layer(state_layer, state_layer_update) # Update column name used by state overlay to look up values this_state_colname = colname thisoverlay.value = "Hover over States for Details" state_overlay = thisoverlay state_layer_update.on_hover(update_state_overlay) return
def update_HSS_area(self): # On change les donnees de Mary if hasattr(self,"dfres"): # On choisit (par defaut) le code WME a afficher pour Mary if self.distance_choice in ["compas","compas_asym"]: variable = "WME" else: variable = "W1" (code,hexc,_) = geo_gv.get_cmap_info(variable) cmap = cm.StepColormap(hexc.values,index=np.asarray(code).astype(float),vmin=code[0],vmax=code[-1]+1) chor_layer = ipyl.Choropleth( geo_data=self.region_geo, choro_data=self.mary_zone.to_dict(), name="zonage sur temps sensible (WME)", value_min = float(code[0]), value_max = float(code[-1]+1), colormap = cmap, border_color='blue', style={'fillOpacity': 0.8, 'dashArray': '5, 5'}, hover_style={"opacity":1,"color":"black","weight":4}) chor_layer.value_min = float(code[0]) chor_layer.value_max = code[-1]*1.0 if hasattr(self,"chor_layer"): if self.chor_layer in self.m.layers: #print("on passe la") self.m.substitute_layer(self.chor_layer,chor_layer) else: #print("ici") self.m.add_layer(chor_layer) else: #print('ou la') self.m.add_layer(chor_layer) self.chor_layer = chor_layer self.chor_layer.on_hover(self.update_chor_html) else: if hasattr(self,"chor_layer") and self.chor_layer in self.m.layers: self.m.remove_layer(self.chor_layer)
def plotLeaflet(geoJson: dict, idToValue: dict, worldMap: lf.Map = None, includeEmpty: bool = True, labelFormat: str = "Id={0} - Value={1}", mapArgs: dict = {}, heatmapArgs: dict = {}) -> lf.Map: ''' Plot the choropleth on the map using the ipyleaflet library @idToValue: a dictionary containing mappings of ids to their associated values @worldMap: ipyleaflet Map object. If this is specified, the new heatmap will be addded to this object. Else a new Map object will be created @includeEmpty: true if we want to display the regions that have value 0. False otherwise @labelFormat: the string format of the text that is displayed when the mouse hovers over a polygon. The format must contain exactly 2 placeholders. Returns: map object ''' updatedIdToValue = __syncIdToValueDict(geoJson, idToValue) # If we don't display empty regions, we need to # create a new geo JSON that does NOT contain the # ids that have 0 value if (not includeEmpty): origGeoJson = geoJson geoJson = {"type": "FeatureCollection", "features": []} for idValue, value in updatedIdToValue.items(): if (value > 0): feature = getFeatureById(origGeoJson, idValue) geoJson["features"].append(feature) # Create the world map object if not specified if (worldMap is None): #basemap=lf.basemaps.CartoDB.DarkMatter, center=center, zoom=10 worldMap = lf.Map(**mapArgs) worldMap.add_control(lf.FullScreenControl()) worldMap.add_control(lf.LayersControl(position="topright")) # Default heatmap arguments minVal, maxVal = min(updatedIdToValue.values()), max( updatedIdToValue.values()) defaultHeatmapArgs = { "key_on": "id", "border_color": "black", "value_min": minVal, "value_max": maxVal, "style": { 'fillOpacity': 0.8, 'dashArray': '5, 5' }, "hover_style": { 'fillColor': 'purple', 'dashArray': '0', 'fillOpacity': 0.5 }, "name": "Choropleth", "colormap": linear.OrRd_06 } # Make a copy of the heatmapArgs, because we would add the default arguments # to this dict if the default arguments are not specified by the caller. Making # a copy prevents modifying the passed in dict object heatmapArgs = dict(heatmapArgs) for k, v in defaultHeatmapArgs.items(): if (k not in heatmapArgs): heatmapArgs[k] = v # Create the choropleth layer choroplethLayer = lf.Choropleth(geo_data=geoJson, choro_data=updatedIdToValue, **heatmapArgs) # Create a label widget to display the currently hovered polygon id & # the value associated with that id labelWidget = widgets.Label(value="") widgetControl = lf.WidgetControl(widget=labelWidget, position="bottomright") worldMap.add_control(widgetControl) def mouseout(*args, **kwargs): ''' Set the label value to empty string when the mouse exits a region ''' labelWidget.value = "" def hover(*args, **kwargs): ''' Set the label to the id & its associated value ''' idValue = kwargs["id"] labelWidget.value = labelFormat.format(idValue, updatedIdToValue[idValue]) # Register callbacks choroplethLayer.on_mouseout(mouseout) choroplethLayer.on_hover(hover) # Remove existing choropleth layer that has the same name choroplethName = heatmapArgs["name"] if ("name" in heatmapArgs) else "" removeLayerByType(worldMap, choroplethName, lf.Choropleth) worldMap.add_layer(choroplethLayer) return worldMap
def brlmap(data, pattern="cod", title="", colormap=linear.YlOrBr_04, legendPosition="bottomright", style={ 'fillOpacity': 1, 'dashArray': '5, 5' }): geo_json_data = __finddictcities(data.keys(), pattern) key_max = max(data.keys(), key=(lambda k: data[k])) key_min = min(data.keys(), key=(lambda k: data[k])) centerX = (geo_json_data["bounds"][0] + geo_json_data["bounds"][2]) / 2 centerY = (geo_json_data["bounds"][1] + geo_json_data["bounds"][3]) / 2 escala = { 1: 360, 2: 180, 3: 90, 4: 45, 5: 22.5, 6: 11.25, 7: 5.625, 8: 2.8125, 9: 1.40625, 10: 0.703125, 11: 0.3515625, 12: 0.17578125, 13: 0.087890625, 14: 0.0439453125, 15: 0.02197265625, 16: 0.010986328125, 17: 0.0054931640625 } difX = abs(geo_json_data["bounds"][2] - geo_json_data["bounds"][0]) difY = abs(geo_json_data["bounds"][3] - geo_json_data["bounds"][1]) if (difY > difX): maiordif = difY * 1.5 else: maiordif = difX ind = 17 while (escala[ind] < maiordif): ind -= 1 m = ipyleaflet.Map(center=(centerY, centerX), zoom=ind) global __data __data = data layer = ipyleaflet.Choropleth(geo_data=geo_json_data, choro_data=data, colormap=colormap, border_color='black', style=style) legend = colormap.scale(data[key_min], data[key_max]) out = widgets.Output() with out: display(legend) m.add_layer(layer) stylesheets = HTML(''' <style> .rigthlgd svg{ float: right; } .rigthlgd{ float: right; text-align: right; } .hiddenTitle { display: none; } </style> ''') elemTitle = HTML(''' <h3 style="text-align: center;">''' + title + '''</h3> ''') if (title == ""): elemTitle.add_class("hiddenTitle") global labelDados labelDados = HTML('<h4><h4>') labelDados.layout.padding = '2px' labelDados.layout.width = '47%' box_legenda = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%') if (legendPosition.find("right") >= 0): out.add_class("rigthlgd") boxLgnd = Box(children=[labelDados, out, stylesheets], layout=box_legenda) else: labelDados.add_class("rigthlgd") boxLgnd = Box(children=[out, labelDados, stylesheets], layout=box_legenda) box_layout = Layout(display='flex', flex_flow='column', align_items='stretch', width='100%') layer.on_hover(__update_html) if (legendPosition.find("bottom") >= 0): box = Box(children=[elemTitle, m, boxLgnd], layout=box_layout) else: box = Box(children=[elemTitle, boxLgnd, m], layout=box_layout) return box
np.percentile(list(choro_map_data_covidxdep.values()), 37.5), np.median(list(choro_map_data_covidxdep.values())), np.percentile(list(choro_map_data_covidxdep.values()), 62.5), np.percentile(list(choro_map_data_covidxdep.values()), 75), np.percentile(list(choro_map_data_covidxdep.values()), 87.5), max(choro_map_data_covidxdep.values()) ], vmin=250, vmax=66000) # In[17]: layercoviddepa = ipyleaflet.Choropleth(geo_data=geo_json_data, choro_data=choro_map_data_covidxdep, colormap=colormap, border_color='black', style={ 'fillOpacity': 0.6, 'dashArray': '5, 5' }) mapacoviddep = ipyleaflet.Map(center=(-10, -70), zoom=4.9) mapacoviddep.add_layer(layercoviddepa) display(mapacoviddep) # **COVID PER CAPITA** # In[18]: xdepartamentos2 = xdepartamentos.sort_values(by='unique_values', ascending=True).drop([10]) xdepartamentos2 = xdepartamentos2.reset_index()
def show(self, **kwargs): """ Generate and return the map object for displaying the map Parameters ----------- None Returns ---------- map:ipyleaflet.Map """ self.map = ipyleaflet.Map( layers=(ipyleaflet.basemap_to_tiles( ipyleaflet.basemaps.CartoDB.Positron),), **kwargs ) choro_layer = ipyleaflet.Choropleth( name=self.dataset, geo_data=self.geo_data, choro_data=self.choro_data[self.selectedAttr][self.selectedYear], colormap=linear.YlOrRd_04, style={ 'opacity': 1, 'weight': 1.9, 'dashArray': '9', 'fillOpacity': 0.5} ) def handle_click(**kwargs): if kwargs['event'] == 'click': clickedFips = kwargs['properties']['GEOID'] clickedName = self.fipsLookUp[clickedFips] dataBox.value = f"{clickedName} : {self.choro_data[self.selectedAttr][self.selectedYear][clickedFips]:,}" self.clickedID = clickedFips choro_layer.on_click(handle_click) # Year select def handle_year_change(change): new_year = str(change.new) choro_layer.choro_data = self.choro_data[self.selectedAttr][new_year] if self.clickedID: clickedName = self.fipsLookUp[self.clickedID] dataBox.value = f"{clickedName} : {self.choro_data[self.selectedAttr][new_year][self.clickedID]:,}" self.selectedYear = new_year yearList = self.availableYearDict[self.selectedAttr] yearListNum = list(map(int, yearList)) minYear = min(yearListNum) maxYear = max(yearListNum) yearSlider, yearWidget = self.yearSlider(minYear, maxYear, maxYear) yearSlider.observe(handle_year_change, 'value') dataBox, dataWidget = self.dataBox() def handle_attr_change(change): new_attr = change.new choro_layer.choro_data = self.choro_data[new_attr][self.selectedYear] if self.clickedID: clickedName = self.fipsLookUp[self.clickedID] dataBox.value = f"{clickedName} : {self.choro_data[new_attr][self.selectedYear][self.clickedID]:,}" self.selectedAttr = new_attr attrDropdown, attrDropdownWidget = self.attrDropdown() attrDropdown.observe(handle_attr_change, "value") # Add to map self.map.add_layer(choro_layer) self.map.add_control(ipyleaflet.LayersControl()) self.map.add_control(ipyleaflet.FullScreenControl()) self.map.add_control(attrDropdownWidget) self.map.add_control(yearWidget) self.map.add_control(dataWidget) return self.map
geo_json_data = load_data( 'https://raw.githubusercontent.com/jupyter-widgets/ipyleaflet/master/examples/us-states.json', 'us-states.json', json.load) unemployment = load_data( 'https://raw.githubusercontent.com/jupyter-widgets/ipyleaflet/master/examples/US_Unemployment_Oct2012.csv', 'US_Unemployment_Oct2012.csv', pd.read_csv) unemployment = dict( zip(unemployment['State'].tolist(), unemployment['Unemployment'].tolist())) layer = ipyleaflet.Choropleth(geo_data=geo_json_data, choro_data=unemployment, colormap=linear.YlOrRd_04, border_color='black', style={ 'fillOpacity': 0.8, 'dashArray': '5, 5' }) m = ipyleaflet.Map(center=(43, -100), zoom=4) m.add_layer(layer) m import seaborn as sns sns.set(style="white") # Load the example mpg dataset mpg = sns.load_dataset("mpg") # Plot miles per gallon against horsepower with other semantics
def renderMap(self): '''creates ipyleaflet map''' self.m = ipyleaflet.Map(center=(33.66832279243364, 135.8861750364304), zoom=10) # self.grid options = [] options.extend(list(self.all_style_dict.keys())) option = options[0] dates = sorted([date for date in self.all_style_dict[option].keys()]) self.layer = ipyleaflet.Choropleth( geo_data=self.grid, choro_data=self.all_style_dict[option][str(dates[0])], colormap=linear.YlOrRd_04, style={ "fillOpacity": 0.8, "dashArray": "5, 5" }, ) self.m.add_layer(self.layer) self.time_slider = widgets.SelectionSlider( options=dates, value=dates[0], description="TimeStamp", disabled=False, continuous_update=False, orientation="horizontal", readout=True, ) self.time_slider.observe(self.on_slide, "value") widget_control_slider = ipyleaflet.WidgetControl( widget=self.time_slider, position="bottomright") self.m.add_control(widget_control_slider) # widgets.interact(update_map_time, timeStamp = self.time_slider) self.dropdown = widgets.Dropdown(options=options, value=option, description="Select layer") self.dropdown.observe(self.on_click, "value") widget_control = ipyleaflet.WidgetControl(widget=self.dropdown, position="topright") self.m.add_control(widget_control) self.color_range = widgets.IntRangeSlider( value=[self.layer.value_min, self.layer.value_max], min=self.layer.value_min, max=self.layer.value_max, step=1, description="ColorBar:", disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format="d", ) self.zoom_to_location({"new": list(self.BBOXes.keys())[0]}) self.color_range.observe(self.on_selection, "value") widget_control = ipyleaflet.WidgetControl(widget=self.color_range, position="bottomright") self.m.add_control(widget_control) locations = widgets.Dropdown( options=self.BBOXes.keys(), value=list(self.BBOXes.keys())[0], description="Location:", ) locations.observe(self.zoom_to_location, "value") widget_control = ipyleaflet.WidgetControl(widget=locations, position="topright") self.m.add_control(widget_control) self.m.observe(self.zoom_out_to_target_bounds, "bounds") def compute_style(feature, colormap, choro_data): return { "fillColor": colormap(choro_data), "color": "white", "weight": random.randint(1, 3), } self.layer.style_callback = compute_style