Skip to content

Instantly share code, notes, and snippets.

@chriddyp
Last active October 9, 2024 00:00
Show Gist options
  • Save chriddyp/3d2454905d8f01886d651f207e2419f0 to your computer and use it in GitHub Desktop.
Save chriddyp/3d2454905d8f01886d651f207e2419f0 to your computer and use it in GitHub Desktop.
# See official docs at https://dash.plotly.com
# pip install dash pandas
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
app = Dash(__name__)
app.layout = html.Div([
dcc.Graph(id='graph-with-slider'),
dcc.Slider(
df['year'].min(),
df['year'].max(),
step=None,
value=df['year'].min(),
marks={str(year): str(year) for year in df['year'].unique()},
id='year-slider'
)
])
@app.callback(
Output('graph-with-slider', 'figure'),
Input('year-slider', 'value'))
def update_figure(selected_year):
filtered_df = df[df.year == selected_year]
fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp",
size="pop", color="continent", hover_name="country",
log_x=True, size_max=55)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
@agouliel
Copy link

Working example:

from dash import Dash, dcc, html, callback
from dash.dependencies import Input, Output
import yfinance as yf

start = '2022-01-01'
end = '2023-01-01'

app = Dash(__name__)

app.layout = html.Div([
dcc.Dropdown(
    id='my-dropdown',
    options=[
        {'label': 'MSFT', 'value': 'MSFT'},
        {'label': 'AAPL', 'value': 'AAPL'},
    ],
    value='MSFT'
),
dcc.Graph(id='my-graph')
], style={'width': '500'})

@callback(Output('my-graph', 'figure'), [Input('my-dropdown', 'value')])
def update_graph(selected_dropdown_value):
    df = yf.download(selected_dropdown_value, start=start, end=end)
    return {
    'data': [{
    'x': df.index,
    'y': df.Close
    }],
    'layout': {'margin': {'l': 40, 'r': 0, 't': 20, 'b': 30}}
    }

app.css.append_css({'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'})

if __name__ == '__main__':
    app.run(debug=True)

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