我在获取参数以继承仪表板中用户下拉选项时遇到麻烦。
下面是我的代码的三个部分。我不认为问题出在布局/绘图部分,因为如果删除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)
答案 0 :(得分:1)
您的回电没问题。
问题是您没有在 getHealth
和 getStew
内返回任何内容。这意味着 None
被隐式返回。
因此更改这些函数以返回用于绘制图形的 DataFames:
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)