I try to create a choropleth with Folium. The choropleth should show the different growth rates of the countries (lower growth rate = dark green, growth rate > 0 = red). In addition, I would like to have a dropdown menu where I can choose between the different years. The default year should be 2016 (or any other, doesn't matter). The dataframe is called final_consumption data (columns = COUNTRY, YEAR, PRODUCT, VALUE, GROWTH_RATE). The colors are still not correct set up, I know. But may main problem is that the dropdown menu doesn't appear and the year is not considered.
Here is the code:
import folium
import ipywidgets as widgets
from IPython.display import HTML, display
import geopandas as gpd
final_consumption_data = data_completed_coordinates[data_completed_coordinates['PRODUCT'] == 'Final
consumption']
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world.to_file("world_countries.geojson", driver='GeoJSON')
geojson_path = "world_countries.geojson"
map_choropleth = folium.Map(tiles='OpenStreetMap', location=[48, 8], zoom_start=2)
choropleth = folium.Choropleth(
geo_data=geojson_path,
name='choropleth',
data=final_consumption_data,
columns=['COUNTRY', 'GROWTH_RATE'],
key_on='feature.properties.name',
fill_color='RdYlGn',
fill_opacity=0.7,
line_opacity=0.2,
legend_name='Consumption growth rate (%)',
highlight=True
).add_to(map_choropleth)
folium.LayerControl().add_to(map_choropleth)
year_dropdown = widgets.Dropdown(options=final_consumption_data['YEAR'].unique(),
value=2016,
description='Year',
disabled=False,
)
def update_choropleth(year):
# print(f"Selected year: {year}")
filtered_data = final_consumption_data[final_consumption_data['YEAR'] == year]
# print(filtered_data.head())
choropleth.geojson.data = filtered_data
choropleth.options['name'] = f'Consumption growth rate (%) for year {year}'
year_dropdown.observe(lambda change: update_choropleth(change.new), names='value')
display(year_dropdown)
display(map_choropleth)
map_choropleth.save('choropleth_interactive.html')
As you can see, I tried some debugging by printing out some steps. The data frame is fine. But the variable year_dropdown and the function update_choropleth seems to have bugs (even if I tried different ways to program it as you might see).
NameError: name 'data_completed_coordinates' is not defined
. It doesn't have to use your data; a toy example is fine if it gives the same behavior as you. However, in order to get help working code makes a big difference.value=2016
tovalue=2015
to get it to even run with that and then it isn't as you describe. I see the dropdown showing up. Of course, since only one year, I cannot choose other year to see if changes. This is why a minimal, reproducible example is described well in How do I ask a good question? in the first bullet point under 'Help others reproduce the problem'. You are supposed to test and have it working to give what you see. I see a dropdown. ....