Getting started with Plotly Dash
This article will focus on locally building and visualising your graph.
What is Plotly Dash?
Let’s start with the basics: what is Plotly Dash? Dash is a Python framework created by Plotly to render interactive dashboards which can also be hosted online, by using just Python. Dash has both an enterprise and an open-source version, we’re going to be using the latter.
There are many advantages of using Plotly Dash, but the three main advantages are:
- Interactivity: with graphs and better storytelling. This allows you to zoom in and out, using filters or other interactive features such as buttons, dropdown menus, etc. All these features are entirely customisable.
- Customisation: of dashboards. Compared to traditional visualisation tools, Plotly Dash gives you the opportunity to have full control of what you’re building. Moreover, Plotly supports Pandas plotting, so in this way, you can also perform complex data transformations before building a visualisation.
- Flexibility: in sharing your dashboard anywhere in the world. At Measurelab we started using Dash for our clients whenever Google Looker Studio isn’t available in a particular country. By using Dash we’re able to build visualisation and deploy them without any geographical constraint.
Let’s get started with Dash
For this tutorial I used a dataset I found on Kaggle which contains the “Top 1000 IMDB Movies” on which I performed some data transformation with Pandas (i.e. dropping columns, data type changes, etc.).
In this tutorial, we’re going to build a bar chart with a dropdown menu where we’ll filter the movies by year.
As a prerequisite to creating your Plotly Dash app, you’ll need first to set up your local environment, so create a new directory where you’ll store the code and set up the virtual environment.
Check if the file needs cleaning. For this specific file, I performed some data transformation, but this won’t be part of this tutorial.
Install Dash, Plotly Express and Pandas. For this tutorial, we’re going to use python3.
pip3 install dash plotly-express pandasCode language: Python (python)
Initialization of your Dash App
Let’s start by creating an empty file named
app.py in the root directory of your project. Save the data in the root directory as well. Below is how your project should be structured.
top_1000_imdb_movies/ | ├── venv/ | ├── app.py | └── movies.csvCode language: Python (python)
app.py import the dependencies
# Import packagesfrom dash import Dash, html, dcc, Input, Output import plotly.express as px import pandas as pdCode language: Python (python)
Read your data with Pandas:
# Read data df = pd.read_csv("movies.csv")Code language: Python (python)
To initialise our app we use this code snippet. This is known as the Dash constructor.
app = Dash(__name__)Code language: Python (python)
The next part we’re going to add is known as the
layout which represents the app components that will be displayed in the browser, from basic HTML components like divs (
html.Div) to complex Dash components like dropdowns (
dcc.Dropdown). The layout consists of a tree of components such as
app.layout = html.Div([ html.H1('Top 1000 IMDB Movies'), html.H4('Gross profit by year'), dcc.Dropdown( id="dropdown", options=df['Released_Year'], value=df['Released_Year'], clearable=False ), dcc.Graph(id="graph") ])Code language: Python (python)
Let’s have a closer look at the elements in our code:
html.H4are HTML tags that will generate for example <h1>Top 1000 IMDB Movies<h1> element in the app.
dcc.Dropdownis a Dash Core component used to generate the dropdown menu. This component comes with an
option(the list options, in this case, the release year of the movie) and a
value(the initial default value in the dropdown).
- The clearable property is usually set to
dcc.Dropdowncomponents. I set it to
Falseto prevent the clearing of the selected dropdown value.
dcc.Graphis another component that renders the data visualisation, the bar chart in this case.
The interactivity of your App
We have defined how our components will be rendered. Time to make our app dynamic. To do so, we’re going to use callback functions. These functions are automatically called by Dash every time an input component’s property changes. In this case, data filtering will trigger the callback function and an output will be returned. So basically a callback function links the inputs and outputs of our App.
"graph", "figure"), Input("dropdown", "value") )Output(Code language: Python (python)
Every time we change the input,
Released_Year in this case, our graph will be updated.
Time to wrap up everything. This last function will help us to create and update the bar chart.
def update_bar_chart(year): release_year = df["Released_Year"] == year fig = px.bar(df[release_year], x="Movie Title", y="Gross Profit", barmode="group", text_auto='.2s') return figCode language: Python (python)
release_year = df["Released_Year"] == yearwe’re setting the value of the df column
"Released_Year"to the argument
- In the second part, we’re using Plotly Express, which is a high-level interface to Plotly, to create the bar chart and its x/y axis values.
To complete the tutorial, we need to add a last part of the code that allows us to run the App.
if __name__ == '__main__': app.run_server(debug=True)Code language: Python (python)
To run our App you run this command
This should be the final result:
Congrats! You’ve just built your first Plotly Dash chart. This is the first step toward creating interactive and fully customizable applications.
If you’d like to learn more about our custom charts services with Plotly Dash, feel free to contact us.