您应该返回一个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)