How to Create Interactive Dashboards in Python

Jim Fay
The Startup
Published in
5 min readOct 18, 2020

An Intro to Dash

Topics

  • What is Dash?
  • Elements of A Dash App
  • Coding a Dash App

What is Dash?

Dash is a Python framework for developing web applications. It’s written on top of Plotly, so any graphs you can create with Plotly are easy to implement in an interactive web app! The potential for dash apps is limitless, and there are plenty of complex and beautiful examples on the Dash App Gallery (source code is available for these projects too).

Today I’ll be breaking down the basic elements of a Dash app, and teach you to code your own simple app. This app will show Wal-Mart store openings across the US over time. The data for this project is available from Plotly here.

Let’s get started!

Elements of a Dash App

  • Components

A Dash Application is made up of various components arranged in a specific layout. These components are visual elements that can take the form of sliders, dropdown menus, graphs, and more. Components are made using HTML (and in some cases JavaScript and CSS too), but coding the components is easy in Python. Just import dash_core_components and/or dash_html_components!

  • Layout

The layout portion of the app arranges the components. Size, color, text, and other general attributes can be set in the layout section of code.

  • Callback

This section of the code adds interactivity to the application by connecting the components to the functions. Take inputs from your components and use the components’ outputs to make adjustments using functions.

  • Functions

The function(s) contain the logic of the interactivity in the app. What do you want to update or change once the user interacts with the components?

Now let’s write some code!

Coding a Dash App

The App We’ll Build Today

  • Our Data

For this example we’ll use data on Wal-Mart openings from 1962 to 2006. We want to create an interactive web app that will show store openings over time in the US. We also want to allow users to filter stores based on year and store type.

  • First Steps

Before diving in to the layout of the app, we initialize the app and set the general style using a pre-made stylesheet.

# Choose Stylesheet
external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css']# Initialize App
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
  • App Layout — Graph

Our first step is to create the graph object (in this case, our map of the US). This part is simple for now. We’ll add the main code for the graph inside of our function.

# Set App Layout
app.layout = html.Div([

# Create Graph object
html.Div([
dcc.Graph(id='my_graph'),
  • App Layout — Dropdown Menu

Next we create the dropdown menu component and define its properties. We set the menu items, make sure that users cannot select more than one option, and set the size of the menu. Make sure to set an id for the component, we’ll reference it later on in the callback section.

# Create Dropdown Menu (Store Type)
html.Div([
dcc.Dropdown(
id='my_dropdown',
options = [
{'label': 'Wal-Mart', 'value': 'Wal-Mart'},
{'label': 'Supercenter', 'value': 'Supercenter'},
{'label': 'All Stores', 'value': 'All Stores'}
],
value='Store Filter',
multi=False,
clearable=False,
style={"width": "50%"}
),
  • App Layout — Range Slider

You get the idea by now! We set the properties of the slider itself, along with its min/max values and step sizes.

# Create Range Slider (Year)
html.Div([
dcc.RangeSlider(
id='my-range-slider',
min=df['YEAR'].min(),
max=df['YEAR'].max(),
step=1,
value=[1996, 2006],
dots=True,
allowCross=False,
marks = {
str(year): {
'label': str(year),
'style': {'color':'#7fafdf'}
}
for year in years_list
}
),
html.Div(id='output-container-range-slider')
])
])
  • Callback

Here we tell the app to recognize the inputs from the dropdown menu and range slider, then convert them into an output that will affect our graph/map.

# Callback
@app.callback(
Output('my_graph','figure'),
[Input('my-range-slider','value'),
Input(component_id='my_dropdown', component_property='value')]
)
  • Function

This section lays out the real functionality of the app. It takes in the inputs from the range slider (years) and the dropdown menu (dd_selection), and filters the data accordingly.

# Update Graph Based on Slider & Dropdown
def build_graph(years, dd_selection):
# Filter Based on Year
df_filtered = df.loc[df['YEAR'] > years[0]]
df_filtered = df_filtered.loc[df['YEAR'] < years[1]]

# Separate DataFrames for Different Store Types
df_walmart = df_filtered.loc[df_filtered['type_store'] == 'Wal-Mart']
df_super = df_filtered.loc[df_filtered['type_store'] == 'Supercenter']

Next, it creates the markers for each store, depending on whether the store is a regular Wal-Mart or a ‘Supercenter’. We use Plotly’s Scattergeo() function to achieve this.

# Place Markers for Wal-Mart Stores
walmart = go.Scattergeo(
name = 'Wal-Mart',
opacity = 0.7,
lon = df_walmart['LON'],
lat = df_walmart['LAT'],
text = df_walmart['city_and_year'],
mode = 'markers',
marker_color = 'lightcoral',
)
# Place Markers for Wal-Mart Supercenters
supercenter = go.Scattergeo(
name = 'Supercenter',
opacity = 0.5,
lon = df_super['LON'],
lat = df_super['LAT'],
text = df_super['city_and_year'],
mode = 'markers',
marker_color = 'midnightblue',
)

To spice things up a little, we can add code to update the graph’s title based on what data is selected!

# Logic for Updating Graph Title & Updating Which Stores are Shown
title_brand = ''

if dd_selection == 'Wal-Mart':
fig = go.Figure(data=walmart)
title_brand = 'Wal-Mart'
elif dd_selection == 'Supercenter':
fig = go.Figure(data=supercenter)
title_brand = 'Supercenter'
else:
fig = go.Figure(data=[walmart, supercenter])
title_brand = 'All Wal-Mart'

Finally, we use the update_layout() function on our map figure to set the size, title, and background color of our map.

Note the code setting geo_scope = ‘usa’. This tells plotly to use its default map of the USA.

# Specify Layout of Map
fig.update_layout(
title = '<b>' + title_brand + ' Locations Opened: ' + str(years[0]) + ' - ' + str(years[1]) + '</b>',
geo_scope='usa',
height = 600,
width = 1400,
showlegend=True,
margin=dict(
l=50,
r=50,
b=100,
t=100,
pad=4),
paper_bgcolor="LightSteelBlue"
)

return fig

Now let’s run our application!

# Run the App
if __name__ == '__main__':
app.run_server(debug=False)

The Final Application

This is a basic application, but being able to code this much will give you the building blocks to make more advanced dashboards in the future. I encourage you to take a look at Dash’s App Gallery for more inspiration.

Sources:

Inspiration

Video Walkthroughs on Coding Dash Apps

Walkthrough of Basic Dash Elements

Dash Documentation

--

--