Introduction to dash data visualization framework.

A framework like no other.

Dash is a framework that uses abstraction to develop HTML / CSS / JS web applications for data visualisation. Primarily developed for Python, the current version also offers development on R, Julia and F#.

The Dash ecosystem was developed by plotly, a Montreal-based company that has been designing analysis and data visualisation tools since 2012. Plotly is best known for its eponymous open-source graph generation library (see plotly).

The strength of the framework lies in its ability to be integrated on top of modern web frameworks such as React, Flask and, of course, Plotly. This makes it possible to integrate data visualisation elements into more traditional web projects, as well as designing small presentations in the form of web applications using only Dash.

Thanks to its low learning curve and the many possibilities it offers in terms of data presentation, this tool is useful both for data scientists and for developers whose primary skill is not data analysis. All you need to do is master the Python language (or other alternatives) and browse the framework’s documentation to be able to present impactful graphs:

As well as enabling graphics to be displayed on a web application, Dash also offers a number of callback methods that allow you to design interactions with the data and the display elements.

The enterprise version of Dash provides a low-code application design tool. The aim is to extend the design of data visualisation applications, by freeing them from technical complexities. We will then look at the open-source version of the framework.

How does a Dash project work and how is it organised?

Dash applications are commonly divided into two sections. The first is called the Layout section. The layout is the fundamental basis of any Dash project. It is made up of a collection of components provided in particular by the dash_html_components and dash_core_components libraries. These two libraries are essential tools for any Dash project.

The second section, which has no name as such, is made up of all the elements that enable interactivity within the application. This is why the layout is often called the application dashboard and the methods in the second section are the callback functions, defining the possible interactions with the dashboard.

Create your first online graph with Dash.

In this presentation, the aim will be to propose a rudimentary interface highlighting a data set on a two-dimensional graph. For interactivity, a parameter bar allows the user to vary the visual aspect of the graph as well as the data presented.

Prepare your development environment for Dash.

Before you can start designing your first Dashboard, you need to install Dash. As far as the necessary tools are concerned, you will need at least a code editor or IDE with Python (Pycharm, Visual Studio Code, Sublime Text, etc.). For your information, it has been possible to use Dash with Jupyter since the release of JupyterDash.

To install Dash, we recommend using the pip package installer, whose installation command is: pip install dash.

If plotly is not installed, it must also be installed using the command: pip install plotly.

In addition, to create a slightly more visual interface, there is a version of Bootstrap dedicated to Dash. The following command adds the required dependencies: pip install dash-bootstrap-components.

Build the basic model for any Dash project.

A Dashboard needs a single python file, in this case called data.py. In this file, we start by importing the elements common to all Dash projects.

from dash import Dash, html, dcc
import dash_bootstrap_components as dbc

html for dash_html_components, is Dash’s Html components module, which allows you to design Html modules using the Python language.

dcc for dash_core_components, is another component module. Like dash_html_components, it offers turnkey interactive components based on javascript, css and html. These components are used to interact with the interface.

dbc or dash_bootstrap_components is the Bootstrap components module that you can add to enhance your interfaces.

Before developing our interface, there is one essential line you must not forget in your Dash project: instantiating the application. To do this, following the imports, please fill in:

app = Dash(__name__)

In addition to the application declaration, add the launch line. This part of the code should appear at the end of the project:

if __name__ = ‘__main__’:
    app.run_server()

During the production phase, we recommend adding the debug=True argument to the run_server() function to make it easier to debug the application.

There’s one last thing that needs to be put in place to complete the Dash project model. This is the layout itself. For now, we’re going to build an empty section using the following command:

app.layout = html.Div([])

Here, using the html module, an empty html div is constructed, all without the need for an .html file. This is how all the html elements of a Dash project are created. In other words, a Dash project is simply the cascading accumulation of components from the html and dcc modules.

Display a static graph in two dimensions.

Before starting to build the Dashboard, you need to load a dataset that can be used in Python. To do this, a common practice is to use the pandas library like this:

# Load csv file with pandas
datas = pd.read_csv('house_data.csv')

If pandas is not recognised, it is highly likely that the library needs to be installed. To do this, use pip: pip install pandas.

Now that the project structure is ready, the next step is to create the layout section, where we will build the page structure.

The first section will simply contain the title of the graphic with an H1 tag:

html.Div([
       html.H1('House Data', style={'font-weight': 'bold', 'font-family': 'Montserrat', 'opacity':'0.7'}),
]),

The example in the title shows how to include children in html components using Dash. It is possible to cascade the declaration of html components indefinitely. This is how a Dash project is structured. To do this, the first argument of an html_components component will always be the children of that component.

The H1 HTML object behaves like all the other Heading objects (H2, H3, H4…). To add a little style to our page, we’re going to use the style parameter. If you’re working on a larger project, it’s perfectly possible to use a class or id naming system and to use a CSS style sheet. Be careful, though, as the CSS in the argument always takes precedence over the imported external css.

The second section will serve as a parameter bar in which we will include two drop-down lists for choosing the columns to be used in our CSV file. A tick box will also be added to choose whether or not to display the curve between the points.

html.Div([
       html.Div([
           html.Label(['Select data in X axis :'], style={'font-weight': 'bold', 'font-family': 'Montserrat', 'opacity':'0.5'}),
           dcc.Dropdown(id="x_axis",
               options=[{'label':value, 'value':value} for value in datas],
               value=datas.columns[0],
               style={'font-weight': '300', 'font-family': 'Montserrat', 'margin-top': '10px'}
           )
       ], style={'width': '20%', 'display': 'inline-block', 'margin-left':'10px', 'vertical-align':'top'}),
 
       html.Div([
           html.Label(['Select data in Y axis :'], style={'font-weight': 'bold', 'font-family': 'Montserrat', 'opacity':'0.5'}),
           dcc.Dropdown(id="y_axis",
               options=[{'label':value, 'value':value} for value in datas],
               value=datas.columns[1],                style={'font-weight': '300', 'font-family': 'Montserrat', 'margin-top': '10px'}
           ),
       ], style={'width': '20%', 'display': 'inline-block', 'margin-left':'50px', 'vertical-align':'top'}),
 
       html.Div([
           html.Label(['Do you want line on your graph ?'], style={'font-weight': '600', 'font-family': 'Montserrat', 'opacity':'0.5'}),
           dcc.Checklist(
               id="line_choice",
               options= [{'label': 'Line', 'value': True}],
               style={'font-weight': '300', 'font-family': 'Montserrat', 'margin-top': '10px'}
           ),
       ], style={'width': '20%', 'display': 'inline-block', 'margin-left':'50px', 'vertical-align':'top'}),
   ], style={ 'background-color': 'white', 'border': '1px solid #F9F9F9', 'padding': '10px', 'margin': '1rem 0rem', 'box-shadow': '0px 0px 30px rgba(0, 0, 0, 0.1)'}),

Let’s look at this example in more detail:

dcc.Dropdown allows you to use a dynamic object to generate a drop-down list. The parameters required for our list are:

id – The indicative term used to link our drop-down list to the modifications made by the callback methods.

options – The argument for declaring the possible choices for the drop-down list with a label and its value. In this case, these are the headings of each of the columns in the CSV file.

value – The value displayed at the beginning without user modification. This allows an initial graph to be displayed before the user modifies the value of the lists.

Lorsque dans le layout sont intégrés des objets dynamiques, il est convenu de leur attribuer des identifiants afin de les utiliser dans les méthodes de callback.

To complete our interface, all that’s left is the section containing the graphic itself. The dcc library already provides an object for this:

html.Div([
       dcc.Graph(id='data_graph', style={'border': '4px solid #F9F9F9'})
    ]),

With this configuration, the essentials for displaying a 2D graphic based on two data fields are in place. As far as the components are concerned, whether static elements for html or dynamic elements for dcc, exhaustive documentation of their parameters and use is presented on the site.

Launch a Dash project and display it in a web browser.

It is now possible to display the graphic on a browser. It will certainly be a static version, but it will be functional. To launch a simulation server and display the graph, run the command in a terminal at the root of the project:

python {name_project} runserver 

A redirect link will then be proposed, and clicking on it will launch a browser and display the graphic.

This is the presentation of a first small web application using Dash. This simple file, which generates a graph by abstraction and is then transformed into a standard web element, can easily be incorporated into other web projects. For example, incorporating Dash into the Django framework is a good way of staying within a Python ecosystem for the purposes of data-processing-oriented web development.

At present, the page only presents the information, but it is not yet possible to modify the items in the drop-down lists. In fact, one of Dash’s major specificities – the interactivity of the graphs – is missing.

Making an interactive graphic is a lot more fun.

The layout is ready, nothing new will be added on this side. All the graphic interactivity will be carried out in the callback section.

This section reacts sequentially, so it is possible to cascade several activities one after the other. In this case, the only desired interaction is to update the graph following a variation in the drop-down lists or the tick box.

First of all, to use callback functions, you need to add new dependencies: from dash.dependencies import Input, Output.

The second step is to declare the callback using the @app.callback() decorator, as well as the Input and Output elements. Each of these elements has two arguments, component_id and component_property.

@app.callback(
   Output('data_graph', 'figure'),
 
   [Input('x_axis', 'value'),
    Input('y_axis', 'value'),
    Input('line_choice', 'value'),],
)

In general, any callback declaration will have this type of configuration. In other words, there are always Outputs first, defining the object and in particular the property which will be impacted, and then a list of Inputs in square brackets, which are also defined as properties within layout objects.

Here, the values of the drop-down lists and the Boolean value of the checkbox are retrieved. In the output, the modification made will have an impact on the graph.

Once the callback has been correctly parameterised, the second step is to declare the method itself.

def update_graph(x_axis, y_axis, line_choice):
   return {
       'data': [dict(
           x = datas[x_axis],
           y = datas[y_axis],
 
           mode = 'lines+markers' if(line_choice is not None and line_choice) else 'markers',
 
           marker = {
               'size': 15,
               'opacity': 0.5,
               'color': 'red'
           }
       )],
 
       'layout': dict(
           xaxis = {
               'title': x_axis,
               'type': 'linear'
           },
           yaxis = {
               'title': y_axis,
               'type': 'linear'
           },
 
           margin = {'l': 40, 'b': 40, 't': 10, 'r': 0},
           hovermode = 'closest'
       )
   }

This update_graph method takes the callback elements as arguments and will generate the graph again using these parameters. Here, the return value will transform the graph by assigning it parameters that are deliberately static and others that are linked to the user’s choices.

The changing parameters are the data with the choices made by the user, the titles of our axes which are simply the terms of the chosen columns and the display mode “marker” or “linear+markers” depending on whether the box has been ticked or not.

That’s all you need to make the graph generator dynamic. By returning to the test URL and varying the choices via the drop-down lists and the tick box, you can see that the graph updates automatically.

It is possible to improve this programme, in particular by adding customisable parameters. For example, the colour of the markers or their size. In this case, simply add the dcc elements to the layout and add the new Inputs to the callback declaration.

Note that if the purpose of a modification is to change another output element, it is sometimes necessary to create a callback chain. This consists of continuing development after the first callback and building others with their own decorator and methods.

When several callbacks follow each other, a third concept is needed to control them all: states. To understand the use of states and their importance, read this more advanced article on Dash: Creating a complete data analysis Dashboard with Dash.

Conclusion.

The Dash framework, coupled with a front-end web framework, gives you the ability to visualise interactive graphs and present much more impactful data to your staff. Even with a rudimentary command of Python, the framework offers a wealth of development opportunities for data visualisation.

This short article covers only the basics. To learn more about the tool, keep an eye out for future releases on the site and take a look at the online documentation, which is fairly intuitive and provides useful examples for everyday use.

Photo Maxime Macé

Maxime Macé

Simple passionné de thématiques diverses et variées. J’apprécie enrichir mes connaissances dans les disciplines techniques comme l’informatique, les sciences et l’ingénierie, mais aussi dans les domaines merveilleux de la philosophie, l’art et la littérature.

Prenons contact

Vous souhaitez me contacter suite à la lecture de cet article ? Merci de renseigner votre adresse électronique et je vous recontacterai dans les plus brefs délais.

CV Ingénieur développeur informatique

CV Étudiant PhD Artificial Intelligence

Portfolio Artist designer