<jupyter_start><jupyter_text>Health, Wealth of Nations from 1800-2008<jupyter_code>import os
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from bqplot import Figure, Tooltip, Label
from bqplot import Axis, ColorAxis
from bqplot import LogScale, LinearScale, OrdinalColorScale
from bqplot import Scatter, Lines
from bqplot import CATEGORY10
from ipywidgets import HBox, VBox, IntSlider, Play, jslink
from more_itertools import flatten<jupyter_output><empty_output><jupyter_text>--- Get Data<jupyter_code>year_start = 1800

df = pd.read_json("data_files/nations.json")
df.head()
list_rows_to_drop = \
(df['income']
 .apply(len)
 .where(lambda i: i < 10)
 .dropna()
 .index
 .tolist()
)

df.drop(list_rows_to_drop, inplace=True)
dict_dfs = {}

for COL in ['income', 'lifeExpectancy', 'population']:
    df1 = \
    DataFrame(df
              .loc[:, COL]
              .map(lambda l: (DataFrame(l)
                              .set_index(0)
                              .squeeze()
                              .reindex(range(1800, 2009))
                              .interpolate()
                              .to_dict()))
              .tolist())
    df1.index = df.name
    dict_dfs[COL] = df1
def get_data(year):
    """
    """
    income = dict_dfs['income'].loc[:, year]
    lifeExpectancy = dict_dfs['lifeExpectancy'].loc[:, year]
    population = dict_dfs['population'].loc[:, year]
    return income, lifeExpectancy, population

get_min_max_from_df = lambda df: (df.min().min(), df.max().max())<jupyter_output><empty_output><jupyter_text>--- Create Tooltip<jupyter_code>tt = Tooltip(fields=['name', 'x', 'y'], 
             labels=['Country', 'IncomePerCapita', 'LifeExpectancy'])<jupyter_output><empty_output><jupyter_text>--- Create Scales<jupyter_code># Income 
income_min, income_max = get_min_max_from_df(dict_dfs['income'])
x_sc = LogScale(min=income_min, 
                max=income_max)

# Life Expectancy 
life_exp_min, life_exp_max = get_min_max_from_df(dict_dfs['lifeExpectancy'])
y_sc = LinearScale(min=life_exp_min, 
                   max=life_exp_max)

# Population
pop_min, pop_max = get_min_max_from_df(dict_dfs['population'])
size_sc = LinearScale(min=pop_min, 
                      max=pop_max)

# Color
c_sc = OrdinalColorScale(domain=df['region'].unique().tolist(), 
                         colors=CATEGORY10[:6])<jupyter_output><empty_output><jupyter_text>--- Create Axes<jupyter_code>ax_y = Axis(label='Life Expectancy', 
            scale=y_sc, 
            orientation='vertical', 
            side='left', 
            grid_lines='solid')

ax_x = Axis(label='Income per Capita', 
            scale=x_sc, 
            grid_lines='solid')<jupyter_output><empty_output><jupyter_text>--- Create Marks 1. Scatter<jupyter_code>cap_income, life_exp, pop = get_data(year_start)
scatter_ = Scatter(x=cap_income, 
                   y=life_exp, 
                   color=df['region'], 
                   size=pop,
                   names=df['name'], 
                   display_names=False,
                   scales={
                       'x': x_sc, 
                       'y': y_sc, 
                       'color': c_sc, 
                       'size': size_sc
                   },
                   default_size=4112, 
                   tooltip=tt, 
                   animate=True, 
                   stroke='Black',
                   unhovered_style={'opacity': 0.5})<jupyter_output><empty_output><jupyter_text>2. Line<jupyter_code>line_ = Lines(x=dict_dfs['income'].loc['Angola'].values, 
              y=dict_dfs['lifeExpectancy'].loc['Angola'].values, 
              colors=['Gray'],
              scales={
                  'x': x_sc, 
                  'y': y_sc
              }, 
              visible=False)<jupyter_output><empty_output><jupyter_text>--- Create Label<jupyter_code>year_label = Label(x=[0.75], 
                   y=[0.10],
                   font_size=50, 
                   font_weight='bolder', 
                   colors=['orange'],
                   text=[str(year_start)],
                   enable_move=True)<jupyter_output><empty_output><jupyter_text>--- Construct the Figure<jupyter_code>time_interval = 10

fig_ = \
Figure(
    marks=[scatter_, line_, year_label], 
    axes=[ax_x, ax_y],
    title='Health and Wealth of Nations', 
    animation_duration=time_interval
)

fig_.layout.min_width = '960px'
fig_.layout.min_height = '640px'

fig_<jupyter_output><empty_output><jupyter_text>--- Add Interactivity- Update chart when year changes<jupyter_code>slider_ = IntSlider(
    min=year_start, 
    max=2008, 
    step=1, 
    description='Year: ', 
    value=year_start)

def on_change_year(change):
    """
    """
    scatter_.x, scatter_.y, scatter_.size = get_data(slider_.value)
    year_label.text = [str(slider_.value)]

slider_.observe(on_change_year, 'value')

slider_<jupyter_output><empty_output><jupyter_text>- Display line when hovered<jupyter_code>def on_hover(change):
    """
    """
    if change.new is not None:
        display(change.new)
        line_.x = dict_dfs['income'].iloc[change.new + 1]
        line_.y = dict_dfs['lifeExpectancy'].iloc[change.new + 1]
        line_.visible = True
    else:
        line_.visible = False
scatter_.observe(on_hover, 'hovered_point')<jupyter_output><empty_output><jupyter_text>--- Add Animation!<jupyter_code>play_button = Play(
    min=1800, 
    max=2008, 
    interval=time_interval
)

jslink(
    (play_button, 'value'), 
    (slider_, 'value')
)<jupyter_output><empty_output><jupyter_text>--- Create the GUI<jupyter_code>VBox([play_button, slider_, fig_])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12800141242937854, 'fraction_numerical': 0.012358757062146893, 'mean_word_length': 2.569628229363579, 'pattern_counts': {'":': 0, '<': 54, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '135', 'license': 'MIT', 'n_tokens_mistral': 2000, 'n_tokens_neox': 1859, 'n_words': 306, 'path': '99-Miscel/02-bqplot-B.ipynb', 'repo_name': 'dushyantkhosla/dataviz', 'size': '5664'}