将破折号下拉选择传递到变量



>我在获取参数以继承仪表板中的用户下拉列表选择时遇到问题。

下面是我的代码的三个部分。我不认为问题出在布局/图形部分,因为如果我删除 Dropdown 对象并显式分配boro变量(即取消注释第 1 节中的第一行(,我能够填充图形。此外,如果我在没有图形的情况下进行测试,并且只是尝试打印变量值,则在使用下拉列表时它仍然显示为空白。

任何人都可以提供一些帮助吗?我正在研究 Plotly Dash 教程 (https://dash.plot.ly/dash-core-components/dropdown( 中给出的示例,但我不确定我是否正确翻译了它们。

第 1 部分:从 API 拉取数据

#boro = 'Bronx'
def getHealth(boro):
health_url = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' +
'$select=health,count(tree_id)' +
'&$where=boroname='' + boro + ''' +
'&$group=health').replace(' ', '%20')
health_trees = pd.read_json(health_url)
def getStew(boro):
stew_url = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' +
'$select=steward,health,count(tree_id)' +
'&$where=boroname='' + boro + ''' +
'&$group=steward,health').replace(' ', '%20')
stew_trees = pd.read_json(stew_url)

第 2 部分:设置布局,创建图形

app.layout = html.Div(children=[
html.H1(children='Trees Overview'),
html.Div(children='''
HEALTH QUALITY
'''),
dcc.Dropdown(
id='dropdown',
options=[{'label': i, 'value': i} for i in trees.boroname.unique()],
value='Bronx',
clearable=False
),
html.Div(id='table-container'),
])
def generateGraphs(df1,df2,df3):
return dcc.Graph(
id='graph1',
figure={
'data': [
go.Pie(labels=df1['health'],values=df1['count_tree_id']),
],
'layout': {
'title': 'Count By Species'
}
}
),
dcc.Graph(
id='graph2',
figure={
'data': [
go.Bar(x=df2[df2['steward']==i]['health']
,y=df2[df2['steward']==i]['count_tree_id']
,name=i
,marker=go.bar.Marker(
color='rgb(26, 118, 255)'
))
for i in df3['steward'].unique()
]
}
)

第3部分:这就是我认为问题所在。我是否正确使用@app.callback功能?我是否正确定义retHealth()并调用generateGraphs()

@app.callback(
dash.dependencies.Output('table-container', 'children'),
[dash.dependencies.Input('dropdown', 'value')])
def retHealth(value):
health=getHealth(value)
stew=getStew(value)
return generateGraphs(health,stew,trees)

你的回调很好。

问题是你不会在getHealthgetStew内返回任何东西。这意味着隐式返回None

因此,更改这些函数以返回用于绘制图形的 DataFame:

def getHealth(boro):
health_url = (
"https://data.cityofnewyork.us/resource/nwxe-4ae8.json?"
+ "$select=health,count(tree_id)"
+ "&$where=boroname='"
+ boro
+ "'"
+ "&$group=health"
).replace(" ", "%20")
return pd.read_json(health_url)

def getStew(boro):
stew_url = (
"https://data.cityofnewyork.us/resource/nwxe-4ae8.json?"
+ "$select=steward,health,count(tree_id)"
+ "&$where=boroname='"
+ boro
+ "'"
+ "&$group=steward,health"
).replace(" ", "%20")
return pd.read_json(stew_url)

最新更新