MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Namespace and Scope
  • The Class
  • Context Managers
  • Inheritance
  • Modules and Packages
  • Virtual Environment
  • Flask
  • Handling Forms with Flask-WTF
  • Jinja
  • Structuring a Flask App
  • Intro to Datastore
  • Intro to AppEngine
  • Flask on App Engine
  • Dash
  • Deploying a Dash App
  • MS Sql Server on Docker

Building Web Dashboards with Plotly Dash

While using JupyterLab or Colab is very convenient for data exploration, it is not a framework for building shareable, interactive applications for a general audience. For that, a web interface is ideal, and Plotly Dash provides a powerful solution.

Plotly Dash is an open-source framework for building data visualization interfaces with pure Python. It's written on top of Flask, Plotly.js, and React.js. You don't need to know HTML, CSS, or JavaScript to create sophisticated, cross-platform, and mobile-ready web applications.

Core Components of a Dash App

Every Dash application is made of two key parts:

  1. The layout: This describes what the application looks like. The layout is a tree of components, like html.Div, dcc.Graph, or dcc.Dropdown. You can think of it as the HTML of your app.
  2. Callbacks: These are Python functions that are automatically called whenever a property of a component changes (e.g., a user selects a new value in a dropdown). Callbacks make your application interactive.

Example 1: A Simple, Static Dashboard

Let's start with the most basic Dash app. It will display a heading, a paragraph, and a pre-rendered chart from Plotly Express.

# main.py
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

# 1. Initialize the Dash app
app = dash.Dash(__name__)
server = app.server # Expose the server variable for Gunicorn

# 2. Create a sample DataFrame
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

# 3. Create a Plotly figure
fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

# 4. Define the app layout
app.layout = html.Div(children=[
    html.H1(children='My First Dash App'),

    html.Div(children='''
        A simple example of a static Dash dashboard.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

# 5. Run the app
if __name__ == '__main__':
    app.run_server(debug=True)

In this example, the app.layout is composed of an H1 title, a Div with text, and a dcc.Graph component that displays our Plotly figure. This app is completely static; the user cannot change anything.


Example 2: Making it Interactive with Callbacks

The real power of Dash is in its interactivity. Let's allow the user to choose what data they want to see on the y-axis of our chart using a dropdown.

This requires a callback. A callback function links an Input (the dropdown's value) to an Output (the graph's figure).

# main.py
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd

app = dash.Dash(__name__)
server = app.server

# Create a more complex DataFrame for this example
df = pd.read_csv('https://plotly.github.io/datasets/country_indicators.csv')

app.layout = html.Div([
    html.H1("Interactive Country Data"),

    html.Div([
        dcc.Dropdown(
            id='yaxis-column',
            options=[{'label': i, 'value': i} for i in ['Fertility rate, total (births per woman)', 'Life expectancy at birth, total (years)']],
            value='Life expectancy at birth, total (years)'
        )
    ]),

    dcc.Graph(id='indicator-graphic')
])

# The Callback
@app.callback(
    Output('indicator-graphic', 'figure'),
    Input('yaxis-column', 'value'))
def update_graph(yaxis_column_name):
    # This function is called every time the dropdown value changes.
    # The new value is passed into the 'yaxis_column_name' argument.
    
    fig = px.scatter(df, x="Year", y=yaxis_column_name,
                     hover_name="Country Name")
    
    fig.update_layout(margin={'l': 40, 'b': 40, 't': 10, 'r': 0}, hovermode='closest')

    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

How it works:

  1. We create a dcc.Dropdown with the id='yaxis-column'.
  2. We create a dcc.Graph with the id='indicator-graphic'.
  3. The @app.callback decorator tells Dash: "Hey, whenever the value property of the component with id='yaxis-column' changes, I want you to run the update_graph function."
  4. Dash then takes the return value of update_graph (which is a Plotly figure) and uses it as the new figure property for the component with id='indicator-graphic'.

Example 3: Advanced Interactivity with Multiple Inputs

You can have multiple inputs control a single output. Let's add radio buttons to let the user switch between a linear and logarithmic scale for the y-axis.

# main.py
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd

app = dash.Dash(__name__)
server = app.server

df = pd.read_csv('https://plotly.github.io/datasets/country_indicators.csv')

app.layout = html.Div([
    html.H1("Advanced Interactivity"),

    html.Div([
        dcc.Dropdown(
            id='yaxis-column-adv',
            options=[{'label': i, 'value': i} for i in ['Fertility rate, total (births per woman)', 'Life expectancy at birth, total (years)']],
            value='Life expectancy at birth, total (years)'
        ),
        dcc.RadioItems(
            id='yaxis-type',
            options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
            value='Linear',
            labelStyle={'display': 'inline-block'}
        )
    ]),

    dcc.Graph(id='indicator-graphic-adv')
])

@app.callback(
    Output('indicator-graphic-adv', 'figure'),
    Input('yaxis-column-adv', 'value'),
    Input('yaxis-type', 'value'))
def update_graph_adv(yaxis_column_name, yaxis_type):
    # This callback now has two inputs. The arguments
    # correspond to the inputs in the same order.
    
    fig = px.scatter(df, x="Year", y=yaxis_column_name,
                     hover_name="Country Name")
    
    fig.update_yaxes(type='linear' if yaxis_type == 'Linear' else 'log')
    
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

Now, the update_graph_adv function runs whenever either the dropdown value or the radio button selection changes. This allows for complex, layered interactions to explore your data.


Deploying Your Dash App

Once you have built your interactive dashboard, the next step is to deploy it to the web so others can access it.

For a detailed guide on how to deploy your Dash application to Google Cloud Platform, please see the next chapter:

  • Deploying a Dash App on GCP

Further Learning

Using Other Visualization Libraries

While Plotly works seamlessly with Dash, you can also use libraries like Matplotlib or Seaborn. You would typically generate the plot, save it as an image in memory, and display the image in your Dash app. For examples, see this repository:

https://github.com/plotly/dash-alternative-viz-demo

Other Web Frameworks

While Dash is excellent for data-heavy dashboards, another popular framework in the Python data science community is Streamlit. It's known for its simplicity and speed for creating simple data apps. You can learn more here:

https://docs.streamlit.io/

Privacy Policy | Terms & Conditions