我正在尝试组合一个 Jupyter Notebook,它允许用户在下拉列表中输入一个州,这会将第二个下拉列表中的结果更改为仅显示该州的城市。选择城市后,可以按下按钮刷新图表(我意识到您可以使用手动进行交互,但无法使其正常运行)并显示结果数据(随着时间的推移covid 案例)。我在制作小部件方面取得了一些成功,但我无法正确绘制数据。
这是我第一次在 Jupyter 中使用小部件,我对交互、交互性、显示和观察(更不用说已弃用的 on_trait_change)有点迷失了。这是我到目前为止所拥有的...
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)