首页 > 解决方案 > 选择下拉值时图表不更新

问题描述

我无法弄清楚为什么我的图表没有使用我选择的值中的数据进行更新。有人可以请尝试帮助。

我已经尝试重写了很多次,但我似乎无法理解我必须在应用回调之后编写的函数以及我应该在这个函数中返回的内容。

app = dash.Dash()

app.layout = html.Div(children = [
    html.H1('Sports PA Dashboard'),

    dcc.Dropdown(
        id='sport_dropdown',
        options=[{'label': i, 'value': i} for i in df.Sport.unique()],
        value = df.Sport.unique()),

    dcc.Graph(id='age_vs_rank')

])

@app.callback(
    dash.dependencies.Output('age_vs_rank', 'figure'),
    [dash.dependencies.Input('sport_dropdown', 'value')])

def update_output(selected_sport):
    print(selected_sport)
    sport = df[df.Sport == selected_sport]
    rank = sport['Rank']
    age = sport['Age']
    dcc.Graph(id='age_vs_rank',
              figure={
                  'data' : [{'x':rank, 'y':age, 'type' : 'bar', 'name' : 'age_vs_rank'}],
                  'layout' : {
                      'title' : 'Age vs Rank'
                  }
              })
if __name__ == '__main__':
    app.run_server(debug=True)

标签: pythonplotly-dash

解决方案


尝试将 return 语句更改为您的 update_output 函数。所以它应该看起来像,

@app.callback(
# If you stuck to what those values belongs to,
# you can specify them more in details:
# Output(component_id='your_plot_here', component_property='children'),
# instead of:
Output('your_plot_here', 'children'),
[Input('sport_dropdown', 'value')])

def update_output(selected_sport):
   sport = df[df.Sport == selected_sport]
   rank = sport['Rank']
   age = sport['Age']
   return figure = {'data': #stuff
                 'layout':#stuff
                }

仅添加数字字典,因为那是唯一要更新的值。

抱歉,如果格式看起来很奇怪,这是我的第一个 StackOverflow 答案:)


推荐阅读