Skip to content

Instantly share code, notes, and snippets.

@chriddyp
Last active July 2, 2019 13:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriddyp/e546a2a2c05df29c868e4cef57fb2105 to your computer and use it in GitHub Desktop.
Save chriddyp/e546a2a2c05df29c868e4cef57fb2105 to your computer and use it in GitHub Desktop.
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import State, Event, Output
from pandas_datareader import data as web
from datetime import datetime as dt
import plotly.graph_objs as go
app = dash.Dash('')
app.layout = html.Div([
dcc.Dropdown(
id='stock-ticker-dropdown-events-example',
options=[
{'label': 'Coke', 'value': 'COKE'},
{'label': 'Tesla', 'value': 'TSLA'},
{'label': 'Apple', 'value': 'AAPL'}
],
value='COKE'
),
dcc.Dropdown(
id='column-selector-events-example',
options=[
{'label': i, 'value': i} for i in
['Open', 'High', 'Low', 'Close', 'High - Low']
],
value='Open'
),
html.Button('Update Graph', id='my-button-events-example'),
dcc.Graph(id='graph-events-example')
])
@app.callback(
Output('graph-events-example', 'figure'),
events=[Event('my-button-events-example', 'click')],
state=[State('stock-ticker-dropdown-events-example', 'value'),
State('column-selector-events-example', 'value')])
def update_graph(stock_ticker, column):
df = web.DataReader(
stock_ticker, 'google',
dt(2017, 1, 1), dt.now()
)
if column != 'High - Low':
y = df[column]
else:
y = df.High - df.Low
return go.Figure(
data=[go.Scatter(x=df.index, y=y)],
layout=go.Layout(
yaxis=go.YAxis(title=column)
)
)
# Run the app
if __name__ == '__main__':
app.run_server(debug=True)
@dansteingart
Copy link

this is really great, thanks! if I were to assign multiple events (e.g. multiple buttons) to the callback, is there a way to tell which button was pressed? e.g. I have a button to update the plot, and one to clear the plot, but they're both trigger the same output graph.

thanks!

@havok2063
Copy link

That's my problem as well. I want to know which input triggers the callback. It doesn't seem like it's possible.

@chriddyp
Copy link
Author

chriddyp commented Jul 5, 2017

Heads up! Author of Dash here 🙂. This pattern of events is likely to be removed from Dash in the future. Right now, it's the only way to do things like button clicks but in the future I'll make buttons stateful with a property like n_clicks. Events is a bit of an anti-pattern in the reactive pattern of Dash and makes things like undo/redo, saved states, and other features more complicated if not impossible. Events also invites odd UIs that could usually be better represented just using persistent stateful controls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment