Week 10 Plotly
Week 10: Plotly in Python
1. Download packages¶
- Install Package in a Anaconda virtual environment
pip install plotly
pip install dash
pip install pandas
2. Introduction¶
3. Import Packages¶
import pandas as pd
import os
import dash
from dash import dcc, Dash, html, dash_table, callback, Output, Input
from dash.dependencies import Input, Output
import plotly.express as px
from dash import dcc
4. Data¶
311 Service Request (https://data.boston.gov/dataset/311-service-requests)
df = pd.read_csv('service_311.csv', encoding='ISO-8859-1')
5. A simple Dash App: Hello World¶
5.1 Code Break Down¶
- This line is known as the Dash constructor and is responsible for initializing your app. It is almost always the same for any Dash app you create.
app = Dash()
- Dash component
Displayed in the web browser and write it as a list
The Div has a few properties, such as children, which we use to add text content to the page: "Hello World"
app.layout = [html.Div(children='Hello World')]
- Running App
debug = True enables some features for development when running a Dash application
- Automatic Reload
- Detailed Error Messages
- Development Features:
if __name__ == '__main__':
app.run(debug=True)
app = Dash()
app.layout = html.Div(children='Hello World', style = {'color':'red'})
if __name__ == '__main__':
app.run(debug=True)
5.2 Open app Locally¶
- Create app.py
- Copy above code to app.py
- Right click and select 'Run Python File in Terminal'
6. Dash App Connecting to Data¶
6.1 Incorporate data¶
We can use many approaches to connect data to an app: APIs, external database, local file, Json file, and more
In below example, we highlight one of the most common ways of incorporating data fram a CSV sheet.
6.2 Code Breakdown¶
- Read the CSV sheet into a pandas dataframe
If data is on your computer, make sure to save it in the same folder that contains the app.py file
df = pd.read_csv('service_31101.csv')
- Apart from page title, we add the DataTable component and read data into the table
Converts the DataFrame into a format compatible with DataTable. to_dict('records') turns each row in df into a dictionary Limits the display to 10 rows per page
dash_table.DataTable(data=df.to_dict('records'), page_size=10)
Example:
Name | Age | City |
---|---|---|
Alice | 24 | New York |
Bob | 30 | Los Angeles |
[
{'Name': 'Alice', 'Age': 24, 'City': 'New York'},
{'Name': 'Bob', 'Age': 30, 'City': 'Los Angeles'}
]
df = pd.read_csv('service_31101.csv')
app = Dash()
# App layout
app.layout = [
html.Div(children='My First App with Data'),
dash_table.DataTable(data=df.to_dict('records'), page_size=10)
]
# Run the app
if __name__ == '__main__':
app.run(debug=True)
7. Visualizing Data¶
The Plotly graphing library has more than 50 chart types to use.
- Import dcc module (DCC stands for Dash Core Components), this module includes a Graph component called dcc. Graph
dcc.Graph is used to do data visualization
- Using plotly.express library to built the histogram chart and assign it to the figure property.
dcc.Graph(figure=px.histogram(df, x = "weekday", barmode='relative', histfunc='count',color='reason'))
df = pd.read_csv('service_31101.csv')
app = Dash()
# App layout
app.layout = [
html.Div(children='My First App with Data'),
dash_table.DataTable(data=df.to_dict('records'), page_size=10),
dcc.Graph(figure = px.histogram(df, x = "weekday", barmode='relative',histfunc='count',color='reason'))
]
# Run the app
if __name__ == '__main__':
app.run(debug=True)
8. Controls and Callbacks¶
Add interactive function to the map by using the callback and function
- Add radio button to the app layout
dcc.RadioItems display a set up radio buttons that let users select on option at time
dcc.RadioItems(options=['daytime', 'nighttime'], value='daytime', id='controls-and-radio-item')
- Build the callback to create the interaction between the radio button and hisogram chart
- callback update app components automatically when specified inputs change.
- callback has two components: 2.1 Input(): callback is triggered wheven the component inside change 2.2 Output(): callback update the propoerty the component
@callback( Output(component_id='controls-and-graph', component_property='figure'), Input(component_id='controls-and-radio-item', component_property='value') ) def update_graph(col_chosen): fig = px.histogram(df, x='continent', y=col_chosen, histfunc='avg') return fig
Add Callabck function to update the app Using if-else to update the app
Empty dcc.Graph Make the dcc.graph empty at the first time
df = pd.read_csv('service_311.csv')
app = Dash()
# App layout
app.layout = [
html.Div(children='My First App with Data'),
dash_table.DataTable(data=df.to_dict('records'), page_size=10),
dcc.RadioItems(options=['daytime', 'nighttime', 'All'], value='All', id='controls-and-radio-item'),
dcc.Graph(figure = {}, id = "controls-and-graph")
]
@callback(
Output(component_id='controls-and-graph', component_property='figure'),
Input(component_id='controls-and-radio-item', component_property='value')
)
def update_graph(time_selected):
if time_selected == 'All':
filter_df = df
else:
filter_df = df[df['time_of_day'] == time_selected]
fig = px.histogram(filter_df, x = "weekday", barmode='relative',histfunc='count',color='reason')
return fig
# Run the app
if __name__ == '__main__':
app.run(debug=True)
9. Styling the app¶
HTML and CSS¶
- Title
style={'textAlign': 'center', 'color': 'blue', 'fontSize': 30}
- Table
html.Div(children =dash_table.DataTable(data=df.to_dict('records'), page_size=10, style_table={'overflowX': 'auto'})),