【问题标题】:How to clear dash figure with callback如何使用回调清除破折号
【发布时间】:2020-07-17 13:22:35
【问题描述】:

我有一个要重置为原始状态的图表,如图所示:

我试过了,好像我打印了图形的初始状态它说无。

app.layout = html.Div([
    html.Div(
        dcc.Graph(id = 'graph')
    )
])
           
@app.callback(
    Output('graph', 'figure'),
    [Input('click', 'clickedData')])
def myfun(x): 
    ...
    return None

但我收到错误:无法读取 null 的属性“布局”

我应该返回什么才能让我的新图表恢复到原来的空状态?

【问题讨论】:

    标签: python python-3.x plotly-dash


    【解决方案1】:

    返回空图应该会有所帮助:fig = {}.
    在回调中只写return {} 而不是return None。

    【讨论】:

    • 请不要回答问题,它们会被误解并标记为“不是答案”。
    【解决方案2】:

    您应该返回一个go.Figure 对象,因为它将被放入dcc.Graph 的figure 属性中。您可以通过将x=[], y=[] 赋予go.Figure 的参数来制作空图:

    @app.callback(Output('graph', 'figure'), [Input('click', 'n_clicks')])
    def myfun(n_clicks):
        if not n_clicks:
            raise dash.exceptions.PreventUpdate
        fig = go.Figure(data=[go.Scatter(x=[], y=[])])
        return fig
    

    (下面是完整的应用代码)

    点击前后

    完整的应用代码

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    import plotly.graph_objs as go
    from dash.dependencies import Input, Output
    
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    
    fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 1, 2])])
    
    app.layout = html.Div(children=[
        html.H1(children='Test app'),
        dcc.Graph(id='graph', figure=fig),
        html.Button('Click to empty', id='click')
    ])
    
    
    @app.callback(Output('graph', 'figure'), [Input('click', 'n_clicks')])
    def myfun(n_clicks):
        if not n_clicks:
            raise dash.exceptions.PreventUpdate
        fig = go.Figure(data=[go.Scatter(x=[], y=[])])
        return fig
    
    
    if __name__ == '__main__':
        app.run_server(debug=True)
    

    【讨论】:

    • 谢谢,这可以清除数字,但它会改变格式。有没有办法将其恢复为仅由 html.Div( dcc.Graph(id = 'graph') ) 创建的原始格式?
    • 回调将改变 figure 属性中的所有内容。如果您想保持一切相似,请使用相同的函数将图形最初创建为dcc.Graph,并在回调中创建空图形。您可以使用任何类型的图形:散点图、条形图等。
    猜你喜欢
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2020-10-21
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    相关资源
    最近更新 更多