【问题标题】:How to populate charts with data on clicking button in Dash with python如何在使用 python 的 Dash 中单击按钮时用数据填充图表
【发布时间】:2020-04-23 00:36:02
【问题描述】:

我正在试验 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)

【问题讨论】:

    标签: python plotly-dash


    【解决方案1】:

    我让它在以下变化中工作:

    使用空的figure 初始化您的图表:

    dcc.Graph(
        id='graph',
        figure={}
    )])
    

    并更改您的回调,使其永远不会返回None,但至少为图形元素返回一个空的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'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多