Some basics of the Plotly Dash framework

Plotly’s Dash framework is used by Python developers to develop complete data apps and interactive dashboards.

Dash uses Flask for the backend and Plotly for producing plots. It also uses React for handling all components. A Dash app is rendered as a single-page React app.

  • Flask: backend server
  • plotly: charting library
  • React: interactive components

Dash can be used to create interactive applications. Dash is not one big pacjage but several packages that handle different aspects on the applications. There are several Dash packages including the following:

  • Dash the main package that provides the backbone of a dash app through the dash.Dash object as well as some tools for managing interactivity and exceptions.
  • Dash Core Components for interactive components that a user of the app can manipulate. (Dropdowns, date pickers, sliders etc)
  • Dash HTML Components provides HTML tags as Python classes.
  • Dash Bootstrap Components (a third party package) for adding Bootstrap functionality to Dash.

To install the main packages:

  • pip install dash will install Dash and the associated packages
  • pip install dash --upgrade to upgrade.

A very simple Hello world dash app:

# imports
import dash
import dash_core_components as dcc
import dash_html_components as html

# app instantiation
app = dash.Dash(__name__)

# app layout: a list of HTML and /or interactive components

app.layout = html.Div([
    html.H1('Hello, World!'),

# callback functions

if __name__ == '__main__':

The general structure of a dash app:

  • a Python file typically called app.py

imports of packages at the top using their commonly-used aliases.

# imports
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Output, Input

App instantiation

  • Creating the app by creating the app variable
  • The __name__ value for the name parameter makes it easy for Dash to locate static assets needed for the app.
# app instantiation
app = dash.Dash(__name__)

App layout

Where the frontend or user-facing elements are set.

  • a container element html.Div that takes a list of components for its children parameter.
  • the children components are usually displayed in the order they are written when the app is rendered.
# app layout: a list of HTML and /or interactive components

app.layout = html.Div([
    html.H1('Hello, World!'),
                 options=[{'label': names, 'value': names}
                          for  name in ['John', 'Joe', 'Jane']]),

Callback functions

  • For the interactivity of the app.
  • Define functions that link the visible elements of the app to each other.
# callback functions
@app.callback(Output('names_output', 'children'),
              Input('names_dropdown', 'value'))
def display_selected_name(name):
    if name is None:
        name = 'nobody'
    return 'You selected ' + name

Running the app

Setting debug=True in the app.run_server method to activate some developer tools used for developing and debugging.

# running the app
if __name__ == '__main__':

Some basics of the data and Layout attributes, configuration. Converting figures.

  • data and Layout are two top-level attributes of Plotly’s Figure object. Each of these attribute has in turn several subattributes.
  • A frames attribute is mainly used for animations. Graphical / geometric shapes are used to express the different attributes of data as well as relationships between the data.

The data attribute

The size, shape and length of shapes express the attributes of the data. The values provided depend on the type of charts so for scatter plots the x and y attributes are provided, latitude and longtitude for maps… You can overlay layers of data on top of each other. Each layer is known a a trace. New traces will take on default colours. Legends are automatically added.

  • add_<chart type> : The methods to add data traces begin with add_ followed by the chart type, e.g. add_scatter(), add_line etc.
  1. First import plotly’s graph_objects module
# import the module.
import plotly.graph_objects as go
  1. Create an empty figure object and add elements to the object. Elements can be added to the go.Figure call.

Alternatively you can assign the object created to a variable and then add to or modify it. (If a Figure object is assigned to a variable it is then available in the global scope and changes can be made to it).

# create an instance of a Figure object and assign to a variable fig
fig  = goFigure()
# add a scatter trace

fig.add_scatter(x=[2,4,6], y = [10,3,6])
# add another scatter trace

fig.add_scatter(x = [4,6,8], y = [20,10,15])

The layout attribute

The layout includes styling elements such as titles, axix, legends, ticks etc. Subattributes such as font size, location etc.

  • Dot notation is used to to access and assign attributes and subattributes.

figure.attribute.sub_attribute = value

  • The figure has a tree like structure.
    • The title attribute falls directly under layout: fig.layout.title`
    • The xaxis and yaxis titles are subattributes: fig.layout.xaxis.title

(To see all the options for the various attributes just use the tab key in a notebook.)

fig.layout.title = "My Figure title"
fig.layout.xaxis.title = "The x-axis title`
fig.layout.yaxis.title = "The y-axis title"

  1. Show the figure
  • Call the show method to display the figure or call the variable, for e.g. fig.show().

  • The show method does provide more options for customising the display of the figure.

  • The show method has a renderer parameter that can be set to JSON. This allows you to interactively explore the Figure object and the top-level data and layout attributes and their subattributes.

Configuration: the config parameter of the Figure object.

The config parameter takes a dictionary with the keys controlling which aspect to modify. The value can be a string or list. Some aspects to control include:

  • displayModeBar defaults to ~True and controls whether to display or not the whole mode bar

  • responsive defaults to True and controls whether or not to change the figure’s dimensions based on the browser window size.

  • toImageButtonOptions controls the default format that can be used when want to download the figure as an image as well as setting default values for height, width, scale, filename etc.

  • modeBarButtonsToRemove a list of buttons to now have in the mode bar.

Converting figures

Plotly figures are HTML objects with JavaScript that makes them interactive. These HTML objects could be downloaded by the users and shared with others.

  • to_ or write_ methods.

  • write_html method to download or share the HTML object

  • write_image method to download an image of the Figure object. This can also be used programatically to create a series of images.

HTML Components

These correspond to HTML tags.

  • children : typically the main and first container of the component’s content and can take a single item or a list of items.
  • className : same as HTML class attribute
  • id : used for interactivity
  • style attribute: similar to HTML stlyle attibute but uses camelCase. Uses a python dictionary for setting several style attributes.

DBC - Dash Bootstrap Components package

The benefits of using Bootstrap include:

  • Themes: Simple to change the theme of an app by adding an external_stylesheets argument to the app creation call.
  • Grid System: Bootstrap’s Grid system to consider the web pages from a user perspective (rows and columns) instead of focusing on screen attributes such as pixels and percentages.
  • Responsiveness: Adapt to different screen sizes. Controls how the size of page elements change as the screen size changes. Can set the width of the column sizes for 5 possible screen sizes:
    • xs : extra small
    • sm : small
    • md : medium
    • lg : large
    • xl : extra large

For example lg=6, md=12 set the width of the column to be 6 out of 12 for large screens and 12 out of 12 screens. dbc.Col(children = [child1, child2, ...], lg=6, md=12) You can also set a column to begin from somewhere other than the left of the screen by using an offset to set the horizontal location on the screen in a dictionary along with the size.

dbc.Col(children = [child1, child2, ...], lg={'size':6, 'offset':2}, md=12)

Multiple columns can be displayed next to each other by placing them in a Row.

A Tabs component is a container for Tab components. A label parameter can be used to specify the label of the tabs.

html.H2('Using Tabs components),
            html.Li('list item 1'),
            html.Li('List item 2')
], label='Tab 1')

  • Encoded colours such as success, info, primary, secondary, danger, light and dark. Bootstraps provides a set of named colours based on the type of information to be conveyed. The colours have a visual meaning to the users. You can still set any colour for the text, background colour or any other element.

Running Dash apps in Jupyter notebooks

  • import JupyterDash object instead of Dash

from jupyter_dash import JupyterDash
app = JupyterDash(__name__)

  • Can run the app in 1 of 3 different modes:

    1. external in a separate browser window
    2. inline in the code output area underneath the code cell
    3. jupyterlab in a separate tab when running JupyterLab
  • Set the width and height using either number of pixels or percentage of screen size.

app.run_server(mode = 'inline', height = 700, width = '70%')

  • app.run_server method takes an optional port argument. This defaults to 8050. If you need to run more than one app during development you can set the port number to run the app on a different server. This also works in jupyter_dash.

A Dropdown component

  • A dropdown component using Dash Core Components

  • the options attribute to set the options that the user can select from.

  • provide a list of dictionaries, one for each option.

    • label is what the user sees
    • value is the actual value
  • link the dropdown to the empty div tag.

  • use a function to take the selected value from the dropdown, process it as an input to the function, do something and then output the return value to an empty div element.

  • Use id values to uniquely identify components.

    • use explicity and descriptive names for the id parameter
  • declare components as Input or Output components.

dcc.Dropdown(id = 'names_dropdown',
            options = [{'label':names, 'value': names}
        for names in ['Mary', 'Jane', 'Joe']]),

Inputs and Outputs

Import Input and Output from dash.dependencies module.

Callback functions


Callback functions are decorators. require 3 things:

  1. Output: the page element to be changed as a result of running the function. The component property can also be specified.
  2. Input: which property of which component to serve as input to the callback function (such as the value property)
  3. A Python function

Define the callback function as an attribute of the app variable using Python classes' dot notation and set the output and input

In Dash, the inputs and outputs of our application are simply the properties of a particular component. See basic-callbacks.

    Output(component_id, component_property),
    Input(component_id, component_property)

A python function to do something with the input and return the output Note: Output must be provided before the Input.

# callback functions
@app.callback(Output('names_output', 'children'),
    Input('names_dropdown', 'value'))
def display_selected_names(name):
    if name is None:
        name = 'Nobody'
    return 'Hello ' + name
  • Dropdown components are useful for creating a dropdown list from a variable in a dataset from which the user can select one or more values. The callback function can then filter the dataset to return something based on the subset of data.

Tech used:
  • Python
  • HTML