From the following files I want to do a map plot by using folium:
Polygons file: https://drive.google.com/file/d/1uhj7OyHktPseR_CtRD0vPfq8HziHA4RK/view? Postcode variable level: https://drive.google.com/file/d/1oFBITKzqLyTvQEASmZmO6CGCOzdPacgH/view?
import pandas as pd
import geopandas as gpd
import folium
df_postcode_variable = pd.read_csv("postcode_sample.csv", dtype=str) # Postcode variable level
df_postcode_variable['people'] = df_postcode_variable['people'].astype(float)
df_polygons = gpd.read_file("postcode_polygons.shp") # Polygons file
df_polygons.crs = "EPSG:4326"
my_map = folium.Map(location=[41.3890727,2.1572654], zoom_start=13,
detect_retina=True, control_scale=False)
folium.Choropleth(
geo_data=df_polygons,
name='choropleth',
data=df_postcode_variable,
columns=['cp','people'],
key_on='cp',
fill_color='OrRd',
fill_opacity=0.5,
line_opacity=0.8,
line_color='Blue',
legend_name='number of people'
).add_to(my_map)
my_map
But I get the following error:
ValueError: key_on `'cp'` not found in GeoJSON.
import pandas_bokeh
pandas_bokeh.output_notebook()
df_joined=df_polygons.merge(df_postcode_variable.set_index('cp'), on='cp')
df_joined.plot_bokeh(simplify_shapes=20000,
category="people",
colormap="Spectral",
hovertool_columns=["cp","people"])
How could I fix this error on folium? cp is in both objects so, It doesnt make sense to me. It seems that is not thetecting cp
in df_polygons
.
If the geodata is in geopandas format, the key is specified as feature.properties.column_name
, as in geojson. See this for details.
my_map = folium.Map(location=[41.3890727,2.1572654], zoom_start=12,
detect_retina=True, control_scale=False)
folium.Choropleth(
geo_data=df_polygons,
name='choropleth',
data=df_postcode_variable,
columns=['cp','people'],
key_on='feature.properties.cp',
fill_color='OrRd',
fill_opacity=0.5,
line_opacity=0.8,
line_color='Blue',
legend_name='number of people'
).add_to(my_map)
my_map