I'm attempting to put together a Jupyter Notebook that allows a user to input a state in a dropdown, which would change the result in the second dropdown to only show cities from that state. Once the city is selected, a button could be pressed to refresh the graph (I realize there's you can use manual with interact, but was unable to get this to function properly) and show the resultant data (covid cases over time). I've had some success making the widgets, but I can't get the data to plot correctly.
This is my first time using widgets in Jupyter and I'm a bit lost what with interact, interactivity, display, and observe (not to mention the deprecated on_trait_change). Here's what I have so far...
from ipywidgets import interact, widgets
from bqplot import pyplot as plt
import pandas as pd
#make example DF
date_list = ['2020-02-01','2020-02-01','2020-02-01','2020-02-01','2020-02-02','2020-02-02','2020-02-02','2020-02-02']
state_list = ['CA','NY','CA','NY','CA','NY','CA','NY']
city_list = ['San Fran','NYC','LA','Albany','San Fran','NYC','LA','Albany']
cases_list = [0,0,0,0,2,6,4,8]
df = pd.DataFrame(index=date_list)
df['state'] = state_list
df['city'] = city_list
df['cases'] = cases_list
#getting unique state and city list sorted in alphabetical order
state_unique = df['state'].unique()
state_unique.sort()
state = widgets.Dropdown(
options=['All'] + list(state_unique),
value='CA', #indicates default starting value
description='State:', #this is the label for the dropdown
)
city = widgets.Dropdown(
description='City:',
)
# function that updates 'city' dropdown depending on value in 'state' dropdown
def list_cities(x):
if state.value == 'All':
city.options = ['']
return city_list
else:
temp = ['All'] + sorted(df.loc[df['state'].eq(state.value),'city'].unique())
city.options = temp
state.observe(list_cities, names = 'value') #the names part tells the observe the change name to look for, this is only looking for value changes
b_refresh = widgets.Button(
description='Refresh',
icon='fa-refresh',
button_style='warning',
layout=widgets.Layout(width='100px')
)
# plotting function
def set_plot(x_data,y_data):
plt.plot(x_data, y_data)
plt.show()
x = list(df.index.unique())
y = df.loc[\
(df['city']==city.value)&\
(df['state']==state.value),'cases']
b_refresh.on_click(set_plot(x, y))
display (state,city,b_refresh)