如何使用 python 在 Dash 中单击按钮时使用数据填充图表

How to populate charts with data on clicking button in Dash with python

我正在试验 Dash/Plotly。我不知道如何通过单击按钮用数据填充图表。我知道,如果我传递相同的东西,我将从我的回调直接返回到应用程序布局中的图形参数,图表就可以工作。我知道我可以获得回调以更改标题文本。我点击了提交按钮,图表没有改变。这是我的代码:

app = dash.Dash(__name__, assets_external_path=assets)

app.layout = html.Div(children=[

    html.Div(className='parent', children=[

        html.Div(className='pD', children=[

           dcc.Dropdown(id='size', options=[
                {'label': 'Small', 'value': 'small'},
                {'label': 'Medium', 'value': 'medium'},
                {'label': 'Large', 'value': 'large'}
            ])

        ]),

        html.Div(className='submit', children=[

            html.Button('Submit', id='submit', n_clicks=0)

        ]),

        html.Div(className='graph_box cD', children=[dcc.Graph(id='graph')])

    ]),

])

@app.callback(
    Output('graph', 'figure'),
    [Input('submit', 'n_clicks')],
    [State('size', 'value')]
)
def update_chart(clicks, size):
    if clicks > 1:        
        return {'data': [{'x': np.random.randint(0, 100, 1000), 'type': 'histogram'}]}

app.run_server(debug=False, port=8000)

我对其进行了以下更改:

用空 figure:

初始化你的图表
dcc.Graph(
    id='graph',
    figure={}
)])

并更改您的回调,使其永远不会 returns None,但至少 returns 为图表元素提供一个空的 figure。将条件更改为使用 clicks 作为简单的真实条件也有帮助。

def update_chart(clicks, size):
    if clicks:
        return {'data': [{'x': np.random.randint(0, 100, 1000), 'type': 'histogram'}]}
    else:
        return {'data': [], 'type': 'histogram'}