Setting up a dash application
newton mbugua
Dashboard graphs
Let’s explore the realm of interactive web applications using Python Dash. Dash is a framework designed for creating web apps with a focus on data visualisation. It works by combining the analytical capabilities of Python with the interactive features of web pages. Let’s see how to setup a minimal app as an introduction to dash.
What is Dash?
Before we dive into the code, let first understand kind of framework dash is and how it came to be. Developed by the team at Plotly, dash is an open-source framework built on top of Flask a python web & API framework, Plotly a visualisation library, and ReactJS a library for building user interfaces. This make dash a perfect tool for creating analytical web applications without requiring extensive knowledge of web development. With Dash, you can create stunning and interactive visualisations with just a few lines of Python code. How you make ask? Let’s setup the app.
Project setup
Create a new directory in your preferred projects folder for your dash app and navigate into it i.e.
1mkdir dash-demo && cd dash-demo
Inside this directory, create a new python file. Let's call it `app.py`.
Installing the dash package
Next let's get dash installed. Open up your terminal or command prompt in your project folder and type:
1pip install dash
This will install the core dash package along with its dependencies.
Writing Your First Dash App
Now comes the fun part 🤩 writing some code! 🧑🏾💻 Open `app.py` in your favourite code editor and start with the following
1#load all libraries
2from dash import Dash, html
3
4# Initialize the Dash app
5app = Dash(__name__)
6
7# Define the app layout
8app.layout = html.Div(children=[
9 html.H1(children='Hello Dash!'),
10
11 html.Div(children='''
12 Dash: This is our gcp-dash project
13 '''),
14])
15
16# Run the app with debug True
17if __name__ == '__main__':
18 app.run(debug=True) #Runs the app only if the code is correct
Here's a quick breakdown of the code above
- We import Dash and HTML components from the dash module. This components give us the power of HTML in a python application.
- We initialise the Dash app. If you are familiar with flask you will notice that this is how we initialise a flask app.
- We define the layout of the app using HTML components provided by Dash. In this case, we're creating a simple page with a header and a paragraph.
- Finally, we run the app with debugging enabled which allows us to make changes to the app without needing to restart the server manually.
Let’s start our application.
Save your `app.py` file and head back to your terminal and run the following command.
1python app.py
If everything is set up correctly, you should see output indicating that the app is running on http://127.0.0.1:8050/. Open this URL in your web browser, and voila! You've just created your first Dash app.
Can we do more ?
Yes. Let's make our app a bit more interesting by adding some interactive components. For example a graph that updates based on user input?
Let's update the `app.py` file to include a dropdown menu and a graph. We shall use one of the most common datasets which is the Iris Dataset. It is a dataset containing four features (length and width of sepals and petals) of 50 samples of three species of Iris (Iris setosa, Iris virginica and Iris versicolor). The goal here is to add a graph showing a scatter chart of the sepal width and sepal length based on the selected species.
1# load all libraries
2from dash import Dash, dcc, html
3from dash.dependencies import Input, Output
4import plotly.express as px
5import pandas as pd
6
7# Initialize the Dash app
8app = Dash(__name__)
9
10# Read your data(in this case iris dataset)
11df = px.data.iris()
12
13# Define the app layout
14app.layout = html.Div(
15 style={"max-width": "800px", "margin": "0 auto"},
16 children=[
17 html.H1(children="Interacting with the Iris Dataset"),
18 dcc.Dropdown(
19 id="species-dropdown",
20 options=[
21 {"label": species, "value": species}
22 for species in df["species"].unique()
23 ],
24 value="setosa",
25 ),
26 dcc.Graph(id="species-graph"),
27 ],
28)
29
30
31# Define callback to update graph
32@app.callback(Output("species-graph", "figure"), [Input("species-dropdown", "value")])
33def update_graph(selected_species):
34 filtered_df = df[df["species"] == selected_species]
35 fig = px.scatter(
36 filtered_df,
37 x="sepal_width",
38 y="sepal_length",
39 title=f"Sepal Width vs. Length: {selected_species}",
40 )
41 return fig
42
43
44# Run the app
45if __name__ == "__main__":
46 app.run(debug=True)
With the updated app save the changes and run your app again with `python app.py`, or if your server is still running then you should see the changes reflect. You should see a drop-down menu and a scatter plot that updates when you select a different species like shown below. Pretty cool, right?
Dash app iris dataset
Conclusion
And there you have it! You've successfully set up and created an interactive web application using Python Dash. From a simple `Hello Dash!` to a dynamic data visualisation tool, you've taken your first steps into the world of Dash which is very exciting.
This article will be part of a series where we showcase dash, build dash templates and use it to solve real world problems. Look out for the next articles where we build a reusable template and another where we introduce a problem and build a dashboard around it.
Happy coding! 🚀
Newton Mbugua
Experienced software developer with nearly half a decade of expertise in full-stack development and a growing passion for data engineering. I have a proven track record of crafting high-quality, scalable software solutions using backend technologies like Node.js and Python, as well as frontend frameworks such as Next JS. I thrive in collaborative environments, bringing energy and a creative aspect to teams to turn innovative ideas into reality. I like to keep up-to date with new technologies and new ways of improving experiences online and continuously expanding my skill set through learning and experimentation.
Recent Posts
Auto Machine Learning in H20
H2O is a user-friendly alternative to Scikit-Learn for machine learning, offering AutoML features that automate data preprocessing, model training, and hyperparameter tuning. It supports both Python and R, making it versatile for various workflows. H2O Flow provides a graphical interface for non-programmers, while extensive documentation aids users in leveraging its capabilities. The article includes practical examples using the Pima Indian Diabetes dataset to build classification models and implement AutoML, demonstrating H2O's effectiveness in simplifying machine learning processes.
john kamau
Oil Prices Predictions in Kenya
Oil prices significantly impact economies, with low prices benefiting importers and high prices aiding exporters. In Kenya, rising kerosene prices have strained low-income households, leading to a 39.45% drop in kerosene usage in 2023. The cost of fuel in Kenya is influenced by product costs, taxes, margins, and distribution, with taxes making up about 40% of prices. Compared to neighbouring countries, Kenya has the highest fuel prices, highlighting the need for targeted interventions and regional cooperation to stabilise fuel costs and support vulnerable populations.
bedan njoroge
Natural Language Processing: a Beginner's Guide
Natural Language Processing (NLP) enables machines to understand and respond to human language, with applications in social media, customer reviews, news articles, and chat applications. Key processing techniques include Bag of Words, TF-IDF, and embeddings. NLP applications encompass sentiment analysis, language translation, topic analysis, text summarisation, named entity recognition, speech recognition, and chatbots. Technologies utilising NLP include Siri, Google Translate, and Grammarly. Understanding NLP basics can enhance project capabilities in working with natural language data.