SlideShare a Scribd company logo
1 of 18
Download to read offline
‘
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

More Related Content

What's hot (20)

Python pandas Library
Python pandas LibraryPython pandas Library
Python pandas Library
 
Knapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmKnapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithm
 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat Sheet
 
Loops in R
Loops in RLoops in R
Loops in R
 
Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly matters
 
26 Computational Geometry
26 Computational Geometry26 Computational Geometry
26 Computational Geometry
 
Python list
Python listPython list
Python list
 
Brute force
Brute forceBrute force
Brute force
 
What is Jupyter Notebook?
What is Jupyter Notebook?What is Jupyter Notebook?
What is Jupyter Notebook?
 
Single linked list
Single linked listSingle linked list
Single linked list
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
Knight's Tour
Knight's TourKnight's Tour
Knight's Tour
 
Binary Search Tree (BST)
Binary Search Tree (BST)Binary Search Tree (BST)
Binary Search Tree (BST)
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Fractional Knapsack Problem
Fractional Knapsack ProblemFractional Knapsack Problem
Fractional Knapsack Problem
 
Binomial Heaps
Binomial HeapsBinomial Heaps
Binomial Heaps
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 

Similar to Dash Intro.pdf

Tech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsTech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsAppsilon Data Science
 
State of the Art Web Mapping with Open Source
State of the Art Web Mapping with Open SourceState of the Art Web Mapping with Open Source
State of the Art Web Mapping with Open SourceOSCON Byrum
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom componentsJeremy Grancher
 
Jetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning TourJetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning TourMatthew Clarke
 
Spark what's new what's coming
Spark what's new what's comingSpark what's new what's coming
Spark what's new what's comingDatabricks
 
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...HostedbyConfluent
 
MongoDB World 2019: Get the Best of Geo Data with MongoDB Atlas and MongoDB C...
MongoDB World 2019: Get the Best of Geo Data with MongoDB Atlas and MongoDB C...MongoDB World 2019: Get the Best of Geo Data with MongoDB Atlas and MongoDB C...
MongoDB World 2019: Get the Best of Geo Data with MongoDB Atlas and MongoDB C...MongoDB
 
Graph computation
Graph computationGraph computation
Graph computationSigmoid
 
Introduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R ShinyIntroduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R Shinyanamarisaguedes
 
Developing Spatial Applications with Google Maps and CARTO
Developing Spatial Applications with Google Maps and CARTODeveloping Spatial Applications with Google Maps and CARTO
Developing Spatial Applications with Google Maps and CARTOCARTO
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)Paul Chao
 
Web3Hub-GDSC presentation.pdf
Web3Hub-GDSC presentation.pdfWeb3Hub-GDSC presentation.pdf
Web3Hub-GDSC presentation.pdfmasa64
 
Data visualization in python/Django
Data visualization in python/DjangoData visualization in python/Django
Data visualization in python/Djangokenluck2001
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8tdc-globalcode
 
Dynamic Graph Plotting with WPF
Dynamic Graph Plotting with WPFDynamic Graph Plotting with WPF
Dynamic Graph Plotting with WPFIJERD Editor
 
Class[3][5th jun] [three js]
Class[3][5th jun] [three js]Class[3][5th jun] [three js]
Class[3][5th jun] [three js]Saajid Akram
 

Similar to Dash Intro.pdf (20)

Tech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsTech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboards
 
State of the Art Web Mapping with Open Source
State of the Art Web Mapping with Open SourceState of the Art Web Mapping with Open Source
State of the Art Web Mapping with Open Source
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
 
Jetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning TourJetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning Tour
 
Om nom nom nom
Om nom nom nomOm nom nom nom
Om nom nom nom
 
Spark what's new what's coming
Spark what's new what's comingSpark what's new what's coming
Spark what's new what's coming
 
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
 
MongoDB World 2019: Get the Best of Geo Data with MongoDB Atlas and MongoDB C...
MongoDB World 2019: Get the Best of Geo Data with MongoDB Atlas and MongoDB C...MongoDB World 2019: Get the Best of Geo Data with MongoDB Atlas and MongoDB C...
MongoDB World 2019: Get the Best of Geo Data with MongoDB Atlas and MongoDB C...
 
Graph computation
Graph computationGraph computation
Graph computation
 
Capstone ms2
Capstone ms2Capstone ms2
Capstone ms2
 
Introduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R ShinyIntroduction to interactive data visualisation using R Shiny
Introduction to interactive data visualisation using R Shiny
 
Developing Spatial Applications with Google Maps and CARTO
Developing Spatial Applications with Google Maps and CARTODeveloping Spatial Applications with Google Maps and CARTO
Developing Spatial Applications with Google Maps and CARTO
 
Novidades do c# 7 e 8
Novidades do c# 7 e 8Novidades do c# 7 e 8
Novidades do c# 7 e 8
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
 
Web3Hub-GDSC presentation.pdf
Web3Hub-GDSC presentation.pdfWeb3Hub-GDSC presentation.pdf
Web3Hub-GDSC presentation.pdf
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Data visualization in python/Django
Data visualization in python/DjangoData visualization in python/Django
Data visualization in python/Django
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
 
Dynamic Graph Plotting with WPF
Dynamic Graph Plotting with WPFDynamic Graph Plotting with WPF
Dynamic Graph Plotting with WPF
 
Class[3][5th jun] [three js]
Class[3][5th jun] [three js]Class[3][5th jun] [three js]
Class[3][5th jun] [three js]
 

Recently uploaded

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 

Recently uploaded (20)

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 

Dash Intro.pdf

  • 1. ‘ DASH AND PLOTLY FOR INTERACTIVE PLOTTING 1 Mayank Tiwari September 15, 2020
  • 2. ‘ 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/
  • 5. ‘ 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
  • 6. ‘ 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
  • 7. ‘ 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
  • 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 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
  • 12. ‘ 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
  • 13. ‘ 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
  • 14. ‘ 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
  • 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
  • 18. ‘ References • https://dash-gallery.plotly.host/Portal/ • https://dash.plotly.com/ • https://plotly.com/python/ • https://github.com/plotly/dash 18