-
-
Save chriddyp/e546a2a2c05df29c868e4cef57fb2105 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
That's my problem as well. I want to know which input triggers the callback. It doesn't seem like it's possible.
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
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!