def run(self): logger.info('Drawing the countrymap') resource_dir = pkg_resources.resource_filename(__package__, shapefile_dir) resource_fname = os.path.join(resource_dir, shapefile_name) df_shapefile_countries = geopandas.GeoDataFrame.from_file( resource_fname) cut_countries = self.handle_data() dataframe = pandas.DataFrame( data=cut_countries.items(), columns=['iso_a2', 'Latency'], ) dataframe.set_index('iso_a2', inplace=True) linear = folium.LinearColormap(['green', 'yellow', 'red'], vmin=0., vmax=120.).to_step(6) countrymap = folium.Map(location=[20, 20], zoom_start=3, min_zoom=2, max_zoom=8, tiles='Mapbox Bright') folium.GeoJson( df_shapefile_countries, style_function=lambda feature: { 'fillColor': self._choose_color(feature, dataframe, linear), 'color': 'black', 'weight': 1, 'fillOpacity': 0.6 }, highlight_function=lambda feature: { 'fillColor': self._choose_color(feature, dataframe, linear), 'color': 'black', 'weight': 3, 'fillOpacity': 0.7, 'dashArray': '5, 5' }).add_to(countrymap) countrymap.add_child(linear) countrymap.save('%s.html' % self.args.filename)
def style_function_40pct_over_100k(x): return { "weight":1, 'color':'black', 'fillColor':'#black' if (x['properties']['100k_to_200k'] + x['properties']['over_200k']) < 40 else colormap(x['properties']['count']), 'fillOpacity':0.7 } m = folium.Map(location=[40, -75.1], zoom_start=11) colormap = folium.LinearColormap( colors=["darkred", "red", "orange","yellow","lightgreen", "green", "darkgreen"], index=[0, 10, 50, 100, 500, 1000, 5000], vmin=merged_areas.loc[merged_areas['count']>0, 'count'].min(), vmax=merged_areas.loc[merged_areas['count']>0, 'count'].max()) fields = ['name', 'count', 'B02001001', 'non_white_pct', 'white_pct', 'black_pct', 'hispanic_pct', 'native_pct', 'asian_pct', 'islander_pct', 'under_50k', '50k_to_100k', '100k_to_200k', 'over_200k'] aliases = ['Tract Name','Observations Count', 'Total Population', 'Non-White %', 'White %', 'Black or African American %', 'Hispanic or Latino %', 'American Indian and Alaska Native %', 'Asian %', 'Native Hawaiian and Other Pacific Islander %', 'Under $50k', '$50k-$100k', '$100k-$200k', 'Over $200k'] tooltip_all = folium.GeoJsonTooltip( fields=fields, aliases=aliases, sticky=True, style="font-family: courier new; color: steelblue;", opacity=0.8, direction='top' )
return minVal def findMax(dictData): maxVal = 0 for i in range(len(dictData["features"])): if dictData["features"][i]["properties"]["POP2005"] > maxVal: maxVal = dictData["features"][i]["properties"]["POP2005"] return maxVal linear = folium.LinearColormap(["green", "yellow", "orange", "red"], index=[ findMax(geo_json_data) / 20, findMax(geo_json_data) / 15, findMax(geo_json_data) / 10, findMax(geo_json_data) ], vmin=findMin(geo_json_data), vmax=findMax(geo_json_data)) fgv = folium.FeatureGroup(name="Volcanoes") for lt, ln, el in zip(lat, lon, elev): fgv.add_child( folium.CircleMarker(location=[lt, ln], radius=6, popup=str(el) + " m", fill_color=colourPoint(el), color="grey", fill_opacity=0.7))
import folium m = folium.Map([41.9901466, -87.6620448], tiles="cartodbpositron", zoom_start=13, max_zoom=14, min_zoom=6, attr="") colormap = folium.LinearColormap(("orange", "white", "purple"), vmin=70, vmax=100, caption="Percent of Families Poverty") colormap.add_to(m) folium.GeoJson(merged_df, style_function=lambda feature: { 'fillColor': colormap(feature['properties']["Poverty Rate"]) if feature["properties"]["Poverty Rate"] else "k", "color": "k", "weight": 0.3, "fillOpacity": 0.4 if feature["properties"]["Poverty Rate"] else 0, }).add_to(m) m.save_html("Poverty Rate")
ax = gdf["ba"].plot(kind="hist", weights=gdf["pop"], normed=True) ax.set_xlabel("BA Fraction") ax.get_figure().savefig('ba_frac.pdf', bbox_inches='tight', pad_inches=0.1) pt = Point(-87.6298, 41.8781) circ = pt.buffer(1.25) ax = gdf[gdf.intersects(circ)].plot(column="density", linewidth=0, scheme="quantiles", k=9, cmap="nipy_spectral") ax.set_axis_off() ax.get_figure().savefig('density.pdf', bbox_inches='tight', pad_inches=0.1) colormap = folium.LinearColormap(("orange", "white", "purple"), vmin=0, vmax=50, caption="Percent Bachelors") m = folium.Map([41.7943, -87.5907], zoom_start=13, tiles="cartodbpositron", max_zoom=14, min_zoom=6, attr="") folium.GeoJson(gdf, style_function=lambda feature: { 'fillColor': colormap(feature['properties']["ba"]) if feature["properties"]["ba"] else "k", "color":
def create_map(df: pd.DataFrame, geotype: str, output_name: str, save: bool = False): """ Input: - df, contains at least: - id (with the code of stadsdeel, gebied, buurtcombinatie or buurt) - value - geotype (string): - stadsdeel - gebied - buurtcombinatie - buurt - output_name (string): how do you want te file to be saved Ouput: html with data on map """ if geotype not in ('buurtcombinatie', 'gebied', 'buurt', 'stadsdeel'): print("geotype wordt niet ondersteund." "Kies een vande volgende opties: " "{buurtcombinatie', 'gebied', 'buurt' of 'stadsdeel'}") return if bool(re.search(r"\W", output_name)): print("ongeldige outputnaam, " "outputnaam mag alleen letters, cijfers of _ bevatten") return df.rename({c: c.lower().strip() for c in df.columns}, inplace=True) if "id" not in df.columns or "value" not in df.columns: print("dataframe moet 'ID' en 'Value' bevatten") return base = 'http://maps.amsterdam.nl/open_geodata/geojson.php?KAARTLAAG=' api_urls = { 'buurt': base + 'GEBIED_BUURTEN&THEMA=gebiedsindeling', 'buurtcombinatie': base + 'GEBIED_BUURTCOMBINATIES&THEMA=gebiedsindeling', 'gebied': base + 'GEBIEDEN22&THEMA=gebiedsindeling', 'stadsdeel': base + 'GEBIED_STADSDELEN&THEMA=gebiedsindeling' } geo_json_data = requests.get(api_urls[geotype]).json() # set colormap linear = folium.LinearColormap( ['#E5F2FC', '#B1D9F5', '#71BDEE', '#00a0e6', '#004699']) colormap = linear.scale(df['value'].min(), df['value'].max()) # convert df to dict df_dict = df.set_index('id')['value'].to_dict() # make map m = folium.Map( location=[52.379189, 4.899431], tiles='https://{s}.data.amsterdam.nl/topo_google/{z}/{x}/{y}.png', attr='Amsterdam', zoom_start=12, min_lat=52.269470, max_lat=52.4322, min_lon=4.72876, max_lon=5.07916, subdomains=['t1', 't2', 't3', 't4']) # plot data on map folium.GeoJson( geo_json_data, style_function=lambda feature: { 'fillColor': colormap(df_dict[feature['properties']['Gebied_code']]) if feature['properties']['Gebied_code'] in df_dict else False, 'color': 'white' if feature['properties']['Gebied_code'] in df_dict else False, 'weight': 1.2, # 'dashArray': '2, 3', 'fillOpacity': 0.6 if feature['properties']['Gebied_code'] in df_dict else 0 }, tooltip=folium.GeoJsonTooltip( fields=['Gebied_code', 'Gebied', 'Opp_m2'], localize=True)).add_to(m) # add scale to map colormap.caption = 'Color scale' colormap.add_to(m) # save map if save: m.save(f'{output_name}.html') return m