In the past, creating analytical Web applications required extensive experience from developers who had knowledge of multiple programming languages and frameworks. Today, you can create data visualization interfaces using only the Python programming language. And one of the popular tools is the Dash (https://dash.plotly.com/introduction).

Dash enables data scientists to present their results in interactive Web applications. You don’t need to be a web development expert. You can build and deploy Dash applications and share them with others in as little as an afternoon.

In this tutorial, you will learn the following:

  • Create a Dash application
  • How do I use Dash core components and HTML components
  • Customize the Dash application style
  • Build interactive applications using callback functions
  • Deploy your application on Heroku

What is Dash?

Dash is an open source framework for building data visualization interfaces. It was released in 2017 as a Python third-party library and has evolved to include versions of R and Julia. Dash enables data analysts to build Web data visualization applications without advanced Web development knowledge.

The following three technologies form the core of Dash:

  • 1.FlaskProvides Web server functionality.
  • 2,React.jsRenders the user interface of the web page.
  • 3,Plotly.jsGenerate charts that you use in your application.

But you don’t have to worry about how to make these technologies work together. Dash will help you, you just need to be able to write Python, R or Julia, and some CSS knowledge.

Canadian company Plotly (https://plotly.com/) founded Dash and supported its development. You may from sharing the names of popular graphics library (https://plotly.com/graphing-libraries/) know the company. Plotly has opened the Dash source code and distributed it under an MIT license, so you can use Dash for free.

Plotly also provides Dash with a paid business partner service called Dash Enterprise. This paid service provides business companies with support services such as hosting, deploying, and handling authentication on Dash applications. But these features aren’t in Dash’s open source ecosystem.

Dash will help you quickly build dashboards. If you’re used to using Python to analyze or visualize data, Dash is a useful addition to your toolbox. Here are some examples you can make with Dash:

  • A dashboard that analyzes trading positions in real timehttps://dash-gallery.plotly.host/dash-web-trader/
  • Visualization of millions of Uber trips

https://dash-gallery.plotly.host/dash-uber-rides-demo/

  • An interactive financial report

https://dash-gallery.plotly.host/dash-financial-report/

These are just a few very simple examples. If you want to see other interesting use cases, please check the Dash App Gallery (https://dash-gallery.plotly.host/Portal/).

Introduction to Dash in Python

In this tutorial, you’ll learn the detailed process of building dashboards using Dash. If you follow these examples, you will move from a quasi-system dashboard on your local computer to a styled dashboard deployed on Heroku.

To build the dashboard, you will use during the period of 2015 to 2018, the United States avocado sales and price data set (https://www.kaggle.com/neuromusic/avocado-prices). The data set used by Justin Kiggins Hass but Avocado Board (https://www.hassavocadoboard.com/retail/volume-and-price-data) provides data sorting.

How do I set the local environment

To develop applications, you need a new directory to store code and data, and a clean Python 3 virtual environment. To create this environment, follow the instructions below and select the version that matches your operating system.

If you are using Windows, open a command prompt and run the following command:

c:\> mkdir avocado_analytics && cd avocado_analytics
c:\> c:\path\to\python\launcher\python -m venv venv
c:\> venv\Scripts\activate.bat
Copy the code

The first command creates a directory for your project and moves the current location to that directory. The second command creates a virtual environment at that location. The last command activates the virtual environment. Be sure to replace the path in the second command with the path of the Python 3 launcher.

If you are using macOS or Linux, perform the following steps from your terminal:

$ mkdir avocado_analytics && cd avocado_analytics
$ python3 -m venv venv
$ source venv/bin/activate
Copy the code

The first two commands do the following:

Create a directory named Avocado_analytics

Move your current location to the Avocado_Analytics directory

3. Create a clean virtual environment venv in this directory

The last command activates the virtual environment you just created.

Next, you need to install the required libraries. You can do this using PIP in a virtual environment. The following installation libraries:

(venv) $ python -m pip install dash==1.133. pandas==1.0. 5
Copy the code

This command will install Dash and PANDAS in your virtual environment. You will use specific versions of these packages to ensure the same environment as the one used in this tutorial. In addition to Dash, PANDAS helps you read and process data that will be used in your application.

Finally, you need some data to enter into the dashboard. Save the data as Mahogany.csv in the root directory of the project. By now, you should have a virtual environment that contains the necessary libraries as well as the data in the project root folder. The structure of your project should look like this:

Avocado_analytics / | ├ ─ ─ venv / | └ ─ ─ but avocado. CSVCopy the code

Next, you’ll build your first Dash application.

How do I build Dash applications

Consider the process of building Dash applications in two steps:

  • Define the appearance of an application based on its layout.
  • Use callback functions to determine which parts of the application are interactive and how they respond.

In this section, you’ll learn about layouts, and in the next section, you’ll learn how to make dashboards interactive. First, set up everything you need to initialize the application, and then define the layout of the application.

Initialize your Dash application

Create an empty file called app.py in the root directory of your project, and then look at the code for app.py in this section.

Here are the first few lines of app.py:

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

data = pd.read_csv("avocado.csv")
data = data.query("type == 'conventional' and region == 'Albany'")
data["Date"] = pd.to_datetime(data["Date"], format="%Y-%m-%d")
data.sort_values("Date", inplace=True)

app = dash.Dash(__name__)
Copy the code

On lines 1 through 4, import the required libraries: DASH, dash_core_components, dash_html_components, and PANDAS. Each library provides a building block for your application:

  • dashHelps you initialize the application.
  • dash_core_componentsAllows you to create interactive components, such as graphics, drop-down lists, or date ranges.
  • dash_html_componentsGives you access to HTML tags.
  • pandasCan help you read and organize data.

In lines 6 through 9, you read the data and preprocess it for use in the dashboard. Some of the data is filtered out because the current version of the dashboard is not interactive, otherwise the values drawn would be meaningless.

On line 11, create an instance of the Dash class. If you’ve used Flask before, initializing the Dash class might look familiar. In Flask, WSGI applications are typically initialized using Flask (__ name__). Similarly, for Dash applications, you can use Dash (__ name__).

Define the layout of the Dash application

Next, you will define the layout properties of the application. This property determines the appearance of your application. In this case, you will use a title with instructions below the title and two charts. The definition is as follows:

app.layout = html.Div(
    children=[
        html.H1(children="Avocado Analytics",),
        html.P(
            children="Analyze the behavior of avocado prices"
            " and the number of avocados sold in the US"
            " between 2015 and 2018",
        ),
        dcc.Graph(
            figure={
                "data": [{"x": data["Date"]."y": data["AveragePrice"]."type""lines"],},"layout": {"title""Average Price of Avocados"},
            },
        ),
        dcc.Graph(
            figure={
                "data": [{"x": data["Date"]."y": data["Total Volume"]."type""lines"],},"layout": {"title""Avocados Sold"},},),])Copy the code

This code defines the Layout property of the App object. This property determines the appearance of the application using a tree structure of Dash components.

Dash components are prepackaged in Python libraries. Some of them will ship with Dash when you install it. You must install the rest separately. In almost every application, you’ll see two sets of components:

1, the Dash HTML Components (https://dash.plotly.com/dash-html-components) provides Python wrapper for the HTML element. For example, you can use this library to create elements, such as paragraphs, headings, or lists.

2, the Dash Core Components (https://dash.plotly.com/dash-core-components) Components to provide you with the Python module for creating interactive user interface. You can use it to create interactive elements, such as graphics, sliders, or drop-down menus.

In lines 13 through 20, you can see the Dash HTML component in action. Start by defining the parent component, html.div. Then, you add two more elements, title (html.h1) and paragraph (html.p), as its children.

These components are equivalent to div, H1, and P HTML tags. You can use the component’s parameters to modify the attributes or contents of the tag. For example, to specify the contents of a div tag, use the children argument in html.div.

There are other parameters in the component, such as style, className, or ID, that refer to attributes of the HTML tag. In the next section, you’ll see how you can use some of these properties to style your dashboard.

The partial layout shown in lines 13 through 20 will be converted to the following HTML code:

<div>
  <h1>Avocado Analytics</h1>
  <p>
    Analyze the behavior of avocado prices and the number
    of avocados sold in the US between 2015 and 2018</p> <! -- Rest of the app --> </div>Copy the code

This HTML code is rendered when you open the application in a browser. It follows the same structure as Python code, with div tags containing h1 and P elements.

In lines 21 through 24 of the layout code snippet, you can actually see the graphical components in the Dash core components. There are two dcc.graph components in app.Layout. The first plotted the average price of avocados over the study period, and the second plotted the number of avocados sold in the United States over the same period.

Behind the scenes, Dash uses Plotly. Js to generate graphics. The dcc.graph component requires a Graph object or Python dictionary that contains the drawing data and layout. In this case, please provide the latter.

Finally, these two lines of code help you run the application:

if __name__ == "__main__":
    app.run_server(debug=True)
Copy the code

Lines 48 and 49 you can run Dash applications locally using Flask’s built-in servers. The debug = True parameter from app.run_server enables the hot-reloading option in your application. This means that when you make changes to the application, it automatically reloads without restarting the server.

Finally, here’s the full version of app.py. You can copy this code into the empty app.py file you created earlier.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

data = pd.read_csv("avocado.csv")
data = data.query("type == 'conventional' and region == 'Albany'")
data["Date"] = pd.to_datetime(data["Date"], format="%Y-%m-%d")
data.sort_values("Date", inplace=True)

app = dash.Dash(__name__)

app.layout = html.Div(
    children=[
        html.H1(children="Avocado Analytics",),
        html.P(
            children="Analyze the behavior of avocado prices"
            " and the number of avocados sold in the US"
            " between 2015 and 2018",
        ),
        dcc.Graph(
            figure={
                "data": [{"x": data["Date"]."y": data["AveragePrice"]."type""lines"],},"layout": {"title""Average Price of Avocados"},
            },
        ),
        dcc.Graph(
            figure={
                "data": [{"x": data["Date"]."y": data["Total Volume"]."type""lines"],},"layout": {"title""Avocados Sold"},},),])if __name__ == "__main__":
    app.run_server(debug=True)
Copy the code

This is the code for the quasi-system dashboard. It includes all the code snippets you examined earlier in this section.

Now it’s time to run your application. Open a terminal in the root directory of the project and in the virtual environment of the project. Run Python app.py, then use your favorite browser to access http:// localhost: 8050.

Successful run! Your dashboard should look like this:

On the plus side, you now have a working version of the dashboard. The bad part is that you still need to do some work to show others. Dashboards are more than just visually pleasing; you still need to add some interactivity to them.

But rest assured, you’ll learn how to solve these problems in the next section.

Read more

Top 10 Best Popular Python Libraries of 2020 \

2020 Python Chinese Community Top 10 Articles \

Top 10 Sand Sculptures and fun GitHub apps \

Special recommendation \

\

Click below to read the article and join the community