#!/usr/bin/env python # coding: utf-8 # In[ ]: import os import json import numpy as np import pandas as pd from ipywidgets import Dropdown from bqplot import Lines, Figure, LinearScale, DateScale, Axis from ipyleaflet import Map, GeoJSON, WidgetControl # In[ ]: data = pd.read_json(os.path.abspath("nations.json")) # In[ ]: def clean_data(data): for column in ["income", "lifeExpectancy", "population"]: data = data.drop(data[data[column].apply(len) <= 4].index) return data def extrap_interp(data): data = np.array(data) x_range = np.arange(1800, 2009, 1.0) y_range = np.interp(x_range, data[:, 0], data[:, 1]) return y_range def extrap_data(data): for column in ["income", "lifeExpectancy", "population"]: data[column] = data[column].apply(extrap_interp) return data # In[ ]: data = clean_data(data) data = extrap_data(data) # In[ ]: data # In[ ]: date_start = pd.datetime(1800, 12, 31) date_end = pd.datetime(2009, 12, 31) date_scale = DateScale(min=date_start, max=date_end) # In[ ]: date_data = pd.date_range(start=date_start, end=date_end, freq="A", normalize=True) # In[ ]: country_name = "Angola" data_name = "income" x_data = data[data.name == country_name][data_name].values[0] # In[ ]: x_scale = LinearScale() lines = Lines(x=date_data, y=x_data, scales={"x": date_scale, "y": x_scale}) ax_x = Axis(label="Year", scale=date_scale, num_ticks=10, tick_format="%Y") ax_y = Axis( label=data_name.capitalize(), scale=x_scale, orientation="vertical", side="left" ) figure = Figure( axes=[ax_x, ax_y], title=country_name, marks=[lines], animation_duration=500, layout={"max_height": "250px", "max_width": "400px"}, ) figure # In[ ]: def update_figure(country_name, data_name): lines.y = data[data.name == country_name][data_name].values[0] ax_y.label = data_name.capitalize() figure.title = country_name # In[ ]: country_name = "Benin" data_name = "income" update_figure(country_name, data_name) # In[ ]: country_name = "Angola" data_name = "population" update_figure(country_name, data_name) # In[ ]: with open("./countries.geo.json") as f: countries = json.load(f) # In[ ]: m = Map(zoom=3) geo = GeoJSON( data=countries, style={"fillColor": "white", "weight": 0.5}, hover_style={"fillColor": "#1f77b4"}, name="Countries", ) m.add(geo) m # In[ ]: widget_control1 = WidgetControl(widget=figure, position="bottomright") m.add(widget_control1) def on_hover(event, feature, **kwargs): global country_name country_name = feature["properties"]["name"] update_figure(country_name, data_name) print("feature",feature) geo.on_hover(on_hover) # In[ ]: dropdown = Dropdown( options=["income", "population", "lifeExpectancy"], value=data_name, description="Plotting:", ) def on_click(change): global data_name data_name = change["new"] update_figure(country_name, data_name) dropdown.observe(on_click, "value") widget_control2 = WidgetControl(widget=dropdown, position="bottomleft") m.add(widget_control2) # In[ ]: