‘
DASH AND PLOTLY
FOR INTERACTIVE
PLOTTING
1
Mayank Tiwari
September 15, 2020
‘
DASH+PLOTLY
2
• Dash is a productive Python framework for building web applications
• Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data
visualization apps with highly custom user interfaces in pure Python
• Dash abstracts away all of the technologies and protocols that are required to
build an interactive web-based application
• Knowledge of HTML & JS is not strictly necessary, but it can help as the function
and call back names of Dash Core Components as it is same as HTML tags & JS
functions
Dash https://plotly.com/dash/
• Plotly is a free and open-source graphing library for Python
• Has many ways to customize graphs
• Works with or without Dash
• Good & illustrated documentation: https://plot.ly/python/
Plotly https://plotly.com/
‘
3
Dash App Gallery
‘
Plot.ly Chart
Gallery
4
Website: https://plotly.com/python/
‘
Dash Installation
pip install dash==1.16.0
A quick note on checking your versions and on upgrading. These docs are run using the
versions listed above and these versions should be the latest versions available. To check
which version that you have installed, you can run e.g.
>>> import dash_core_components
>>> print(dash_core_components.__version__)
5
‘
Hello Dash!
import dash
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div('Hello Dash!')
if __name__ == '__main__':
app.run_server()
6
‘
Dash – Main Components
 Layout (UI) - describes what the application looks like
 Html components: https://dash.plotly.com/dash-html-
components
 Core components: https://dash.plotly.com/dash-core-
components
 Callbacks - describes the interactivity of the application
7
‘
Dash Layout
HTML ... in Python
import dash_html_components as html
app.layout = html.Div(children=[
html.H1(
'Hello Dash',
style={'text-align': 'center'}),
html.Div(
id='my-div',
children='Dash: A web app
framework for Python. ',
style={'textAlign': 'center'}),
]
)
8
‘
Dash Layout
HTML ... in Python ... plus core components
import dash_core_components as dcc
component1 = dcc.Dropdown(value='MTL', options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': 'Montréal', 'value': 'MTL'},
{'label': 'San Francisco', 'value': 'SF'}])
component2 = dcc.Checklist(value=['MTL'], options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': 'Montréal', 'value': 'MTL'},
{'label': 'San Francisco', 'value': 'SF'}])
component3 = dcc.Slider(min=0, max=9, value=5)
component4 = dcc.Tabs(value='tab-2-example', children=[
dcc.Tab(label='tab one', value='tab-1-example', children=[
component1,
component3
]),
dcc.Tab(label='tab two', value='tab-2-example', children=component2)])
app.layout = html.Div(component4)
9
‘
Dash Core Component -
Graphs
Core component that accepts plotly.py go.Figure object!
import dash_core_components as dcc
import plotly.graph_objs as go
import dash
app = dash.Dash()
app.layout = html.Div(children=[
html.H1('Hello Graph', style={'text-align': 'center’}),
dcc.Graph(
id='my-first-graph’,
figure=dict(data=[dict(x=[0, 1, 2], y=[3, 4, 2])])
)
])
if __name__ == '__main__':
app.run_server()
10
‘
Scatter Plot Graph Example
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.express as px
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df =
pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
fig = px.scatter(
df, x="gdpPercap", y="lifeExp", size="pop",
color="continent", hover_name="country", log_x=True, size_max=60)
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
11
‘
Callbacks
Callbacks are Python functions that are automatically
called by Dash whenever an input component's property
changes.
Reference: https://dash.plotly.com/basic-callbacks
12
‘
Dash Callbacks
You can get callbacks from
• Button Clicks, Text(Div/P) clicks
• Dropdown list value entered/changed
• Graph Hover/Click on Value
• Period timers, URL address change,…
From Dash Callbacks, you can
• Update input values
• Generate new HTML elements
• Update the CSS style of the layout HTML elements
• Generate any kind of plot.ly graph
13
‘
Callbacks - Example
from dash.dependencies import Input, Output
df =
pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv
')
@app.callback(
Output('life-exp-vs-gdp', 'figure'),
Input('year-slider', 'value')
)
def update_figure(selected_year):
filterDf = df[df.year == selected_year]
fig = px.scatter(filterDf, x="gdpPercap", y="lifeExp", size="pop", color="continent",
hover_name="country", log_x=True, size_max=60)
fig.update_layout(transition_duration=500)
return fig
app.layout = html.Div([
dcc.Graph(id='life-exp-vs-gdp'),
dcc.Slider(
id='year-slider', min=df['year'].min(), value=df['year'].min(),
max=df['year'].max(), marks={str(year): str(year) for year in df['year'].unique()}, step=None
)
])
14
‘
Callback - Linking
@app.callback(
Output('year-pop', 'figure'),
[dash.dependencies.Input('life-exp-vs-gdp', 'hoverData')]
)
def update_output_div(hoverData):
if not hoverData:
country = ''
else:
country = hoverData['points'][0]['hovertext']
filterDf = df[df.country == country]
fig = px.bar(filterDf, x='year', y='pop', title='Year Vs Population: {}'.format(country))
# return 'Output: {}'.format(hoverData['points'][0]['hovertext'])
return fig
app.layout = html.Div([
dcc.Graph(id='life-exp-vs-gdp'),
dcc.Slider(
id='year-slider', min=df['year'].min(), value=df['year'].min(),
max=df['year'].max(), marks={str(year): str(year) for year in df['year'].unique()}, step=None
),
dcc.Graph(id='year-pop'),
])
15
‘
16
‘
17
‘
References
• https://dash-gallery.plotly.host/Portal/
• https://dash.plotly.com/
• https://plotly.com/python/
• https://github.com/plotly/dash
18

Dash Intro.pdf

  • 1.
    ‘ DASH AND PLOTLY FORINTERACTIVE PLOTTING 1 Mayank Tiwari September 15, 2020
  • 2.
    ‘ DASH+PLOTLY 2 • Dash isa productive Python framework for building web applications • Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data visualization apps with highly custom user interfaces in pure Python • Dash abstracts away all of the technologies and protocols that are required to build an interactive web-based application • Knowledge of HTML & JS is not strictly necessary, but it can help as the function and call back names of Dash Core Components as it is same as HTML tags & JS functions Dash https://plotly.com/dash/ • Plotly is a free and open-source graphing library for Python • Has many ways to customize graphs • Works with or without Dash • Good & illustrated documentation: https://plot.ly/python/ Plotly https://plotly.com/
  • 3.
  • 4.
  • 5.
    ‘ Dash Installation pip installdash==1.16.0 A quick note on checking your versions and on upgrading. These docs are run using the versions listed above and these versions should be the latest versions available. To check which version that you have installed, you can run e.g. >>> import dash_core_components >>> print(dash_core_components.__version__) 5
  • 6.
    ‘ Hello Dash! import dash importdash_html_components as html app = dash.Dash() app.layout = html.Div('Hello Dash!') if __name__ == '__main__': app.run_server() 6
  • 7.
    ‘ Dash – MainComponents  Layout (UI) - describes what the application looks like  Html components: https://dash.plotly.com/dash-html- components  Core components: https://dash.plotly.com/dash-core- components  Callbacks - describes the interactivity of the application 7
  • 8.
    ‘ Dash Layout HTML ...in Python import dash_html_components as html app.layout = html.Div(children=[ html.H1( 'Hello Dash', style={'text-align': 'center'}), html.Div( id='my-div', children='Dash: A web app framework for Python. ', style={'textAlign': 'center'}), ] ) 8
  • 9.
    ‘ Dash Layout HTML ...in Python ... plus core components import dash_core_components as dcc component1 = dcc.Dropdown(value='MTL', options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': 'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'}]) component2 = dcc.Checklist(value=['MTL'], options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': 'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'}]) component3 = dcc.Slider(min=0, max=9, value=5) component4 = dcc.Tabs(value='tab-2-example', children=[ dcc.Tab(label='tab one', value='tab-1-example', children=[ component1, component3 ]), dcc.Tab(label='tab two', value='tab-2-example', children=component2)]) app.layout = html.Div(component4) 9
  • 10.
    ‘ Dash Core Component- Graphs Core component that accepts plotly.py go.Figure object! import dash_core_components as dcc import plotly.graph_objs as go import dash app = dash.Dash() app.layout = html.Div(children=[ html.H1('Hello Graph', style={'text-align': 'center’}), dcc.Graph( id='my-first-graph’, figure=dict(data=[dict(x=[0, 1, 2], y=[3, 4, 2])]) ) ]) if __name__ == '__main__': app.run_server() 10
  • 11.
    ‘ Scatter Plot GraphExample import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import plotly.express as px external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv') fig = px.scatter( df, x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=60) app.layout = html.Div([ dcc.Graph( id='life-exp-vs-gdp', figure=fig ) ]) if __name__ == '__main__': app.run_server(debug=True) 11
  • 12.
    ‘ Callbacks Callbacks are Pythonfunctions that are automatically called by Dash whenever an input component's property changes. Reference: https://dash.plotly.com/basic-callbacks 12
  • 13.
    ‘ Dash Callbacks You canget callbacks from • Button Clicks, Text(Div/P) clicks • Dropdown list value entered/changed • Graph Hover/Click on Value • Period timers, URL address change,… From Dash Callbacks, you can • Update input values • Generate new HTML elements • Update the CSS style of the layout HTML elements • Generate any kind of plot.ly graph 13
  • 14.
    ‘ Callbacks - Example fromdash.dependencies import Input, Output df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv ') @app.callback( Output('life-exp-vs-gdp', 'figure'), Input('year-slider', 'value') ) def update_figure(selected_year): filterDf = df[df.year == selected_year] fig = px.scatter(filterDf, x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=60) fig.update_layout(transition_duration=500) return fig app.layout = html.Div([ dcc.Graph(id='life-exp-vs-gdp'), dcc.Slider( id='year-slider', min=df['year'].min(), value=df['year'].min(), max=df['year'].max(), marks={str(year): str(year) for year in df['year'].unique()}, step=None ) ]) 14
  • 15.
    ‘ Callback - Linking @app.callback( Output('year-pop','figure'), [dash.dependencies.Input('life-exp-vs-gdp', 'hoverData')] ) def update_output_div(hoverData): if not hoverData: country = '' else: country = hoverData['points'][0]['hovertext'] filterDf = df[df.country == country] fig = px.bar(filterDf, x='year', y='pop', title='Year Vs Population: {}'.format(country)) # return 'Output: {}'.format(hoverData['points'][0]['hovertext']) return fig app.layout = html.Div([ dcc.Graph(id='life-exp-vs-gdp'), dcc.Slider( id='year-slider', min=df['year'].min(), value=df['year'].min(), max=df['year'].max(), marks={str(year): str(year) for year in df['year'].unique()}, step=None ), dcc.Graph(id='year-pop'), ]) 15
  • 16.
  • 17.
  • 18.
    ‘ References • https://dash-gallery.plotly.host/Portal/ • https://dash.plotly.com/ •https://plotly.com/python/ • https://github.com/plotly/dash 18