Skip to content

Instantly share code, notes, and snippets.

@chriddyp
Last active December 11, 2024 14:58
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)
@rohansb
Copy link

rohansb commented Jun 22, 2017

found that this example works only after following dependencies are installed:
pip install plotly==2.0.11 pip install dash==0.17.5 pip install dash_renderer pip install dash_html_components pip install pandas_datareader

@chriddyp
Copy link
Author

chriddyp commented Jun 26, 2017

For more about how this example works and how to install the necessary dependencies, please see the official dash user guide at https://dash.plotly.com. Thank you!

@PierreBourgault
Copy link

PierreBourgault commented Jul 8, 2017

The user guide instructions for the installation at https://plot.ly/dash is very specific about which version of each library to install. Do you know if we could just install those libraries without specifying the version?

@jkhosla
Copy link

jkhosla commented Aug 4, 2017

@PierreBourgault You could install without version numbers - it works for the current setup . But may fail in the future.

@lassebv
Copy link

lassebv commented Nov 30, 2017

Am I the only that gets an error like this when running the example? The error seems to be from fetching the data to plot.
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf8 in position 359: invalid start byte`

@cosmik2002
Copy link

It looks like Google problem, try yaho. Work fine for me
df = web.DataReader(
selected_dropdown_value,
'yahoo',
dt(2017, 1, 1),
dt.now()
)

@sanbelief
Copy link

how to run a dash application can anybody tell me coz i am getting an error while running the code on jupyter i.e. system exit and also tell me from where i can access the app

@MattKovtun
Copy link

Not 'google' nor 'yahoo' is currently working, please provide some valid source

@doursand
Copy link

doursand commented Apr 1, 2018

you can use quandl instead , ex below 👍

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html

from pandas_datareader import data as web
from datetime import datetime as dt
import quandl

app = dash.Dash('Hello World')

app.layout = html.Div([
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'Poxel', 'value': 'EURONEXT/POXEL'},
{'label': 'Orange', 'value': 'EURONEXT/ORA'},
{'label': 'TechnipFMC', 'value': 'EURONEXT/FTI'}
],
value='Poxel'
),
dcc.Graph(id='my-graph')
], style={'width': '500'})

@app.callback(Output('my-graph', 'figure'), [Input('my-dropdown', 'value')])
def update_graph(selected_dropdown_value):
df = quandl.get(
selected_dropdown_value,
authtoken="your_access_token_after_registering_to_quandl"
)
return {
'data': [{
'x': df.index,
'y': df.Last
}],
'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_server()

@JiaWenShiboy
Copy link

It works

@yelled1
Copy link

yelled1 commented Jul 26, 2018

Installed all dependencies, but I get the following error from my jupyter lab.
Using pipenv with Google Cloud VM & Ubuntu 16.04
Thanks,

UnsupportedOperation Traceback (most recent call last)
in ()
37
38 if name == 'main':
---> 39 app.run_server()

~/.local/share/virtualenvs/simulation-RVBo82bs/lib/python3.6/site-packages/dash/dash.py in run_server(self, port, debug, **flask_run_options)
566 debug=False,
567 **flask_run_options):
--> 568 self.server.run(port=port, debug=debug, **flask_run_options)

~/.local/share/virtualenvs/simulation-RVBo82bs/lib/python3.6/site-packages/flask/app.py in run(self, host, port, debug, load_dotenv, **options)
936 options.setdefault('threaded', True)
937
--> 938 cli.show_server_banner(self.env, self.debug, self.name, False)
939
940 from werkzeug.serving import run_simple

~/.local/share/virtualenvs/simulation-RVBo82bs/lib/python3.6/site-packages/flask/cli.py in show_server_banner(env, debug, app_import_path, eager_loading)
627 message += ' (lazy loading)'
628
--> 629 click.echo(message)
630
631 click.echo(' * Environment: {0}'.format(env))

~/.local/share/virtualenvs/simulation-RVBo82bs/lib/python3.6/site-packages/click/utils.py in echo(message, file, nl, err, color)
257
258 if message:
--> 259 file.write(message)
260 file.flush()
261
UnsupportedOperation: not writable

@nahal626
Copy link

nahal626 commented Oct 4, 2018

I'm running the above code using Spyder/Anaconda. When opening local host on port 8050, I only see a White window with "Loading..." on the top. Can anyone please help me?

@mstorry
Copy link

mstorry commented Nov 1, 2018

datasource 'yahoo' works for me currently (Google does not)

@PeterKoppelman
Copy link

I seem to be getting hung up at the decorator and the def update_graph. I get the * Running on http://127.0.0.1:8050/ (Press CTRL+C to quit) and then the program hangs.

Any ideas?

@sashahuni
Copy link

How about if i would like to use a dataset on that sample code?

@sashahuni
Copy link

How about if i would like to use a dataset on that sample code?

@aboucher410
Copy link

HELP PLEASE! I am a student and I trying to create a graph to show volunteer impacts. Nothing fancy. I tried the simple graph and that didn't work, now I have this one and its not working :(

ModuleNotFoundError Traceback (most recent call last)
in
4 import dash_html_components as html
5
----> 6 import pandas.io.data as web
7
8

ModuleNotFoundError: No module named 'pandas.io.data'

@egenius01
Copy link

how to run a dash application can anybody tell me coz i am getting an error while running the code on jupyter i.e. system exit and also tell me from where i can access the app

use the command prompt in running your code also i dont advise you use jupyter for coding or running dash.
on your command promt just navigate to your file.

ALSO

this worked for me:
just click the file it's going to run as executable

@sunnyliu33
Copy link

I'm running the above code using Spyder/Anaconda. When opening local host on port 8050, I only see a White window with "cannot connect..." on the top. Can anyone please help me?

@msa9493
Copy link

msa9493 commented Mar 11, 2020

Hi, can anyone tell why google isnt working and yahoo is?

@zormit
Copy link

zormit commented Sep 5, 2020

Hi, can anyone tell why google isnt working and yahoo is?

apparently google is not available as a data source anymore, but yahoo still is pydata/pandas-datareader#768

@vhxs
Copy link

vhxs commented Mar 11, 2022

Can confirm that as of 2022 google doesn't work but yahoo does.

@skchronicles
Copy link

Hello there,
I just have a quick question. Is there a way to export the resulting report/dashboard as a standalone html file (something with all assets bundled), or does dash require some server-side processing via python? I have seen some efforts to get python running in the browser via webassembly; however, I am not sure if dash already supports this out of the box or not.
I have been using a combination of Rmarkdown/quarto with python and plotly to create dashboard-like reports. The nice thing with Rmarkdown/quarto is that you can export everything as a stand alone html file, which is nice when working with collaborators. Just email them a report, and they can open it with Chrome.

Anyways, please let mw know what you think, and have a great day!

Best Regards,
@skchronicles

@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