Introduction to Dash in Python - GeeksforGeeks

Introduction to Dash in Python

Last Updated : 10 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Dash is a Python framework for building analytical web applications. Dash helps in building responsive web dashboards that is good to look at and is very fast without the need to understand complex front-end frameworks or languages such as HTML, CSS, JavaScript. Let’s build our first web dashboard using Dash.

Installation and Imports

Install the latest version of Dash

pip install dash

Basic Dashboard

In this section, we will make an app that shows a static(but responsive) graph on the web page using the dash.

Step 1: Importing all the required libraries
Now let’s import Dash, Dash Core Components(which has components like graph, inputs etc., ) and Dash HTML Components(which has HTML components like meta tags, body tags, paragraph tags etc., )




# importing required libraries
import dash
import dash_core_components as dcc    
import dash_html_components as html


Step 2: Designing a layout
HTML components are just like HTML. Here html.H1 refers to the h1 tag in HTML.
Then, we make a graph which has various parameters such as id(a unique ID to a particular graph), figure(the graph itself), layout(the basic layout, title of graph, X axis, Y axis data etc., ).

  • The figure parameter is essentially a dictionary which has elements like x, y, type, name.
  • x refers to the X-axis value(it can be a list or a single element), y is the same except it is associated with the Y-axis.
  • The type parameter refers to the type of the graph, it maybe line, bar.
  • The name parameter refers to the name associated with the axis of a graph




app = dash.Dash()
  
app.layout = html.Div(children =[
    html.H1("Dash Tutorial"),
    dcc.Graph(
        id ="example",
        figure ={
            'data':[
                       {'x':[1, 2, 3, 4, 5],
                        'y':[5, 4, 7, 4, 8],
                        'type':'line'
                        'name':'Trucks'},
                       {'x':[1, 2, 3, 4, 5], 
                        'y':[6, 3, 5, 3, 7], 
                        'type':'bar',
                        'name':'Ships'}
                   ],
            'layout':{
                'title':'Basic Dashboard'
            }
        }
    )
])


Step 3: Running the server
The dashboard is now ready, but it needs a server to run on. Thus we set up the server using the below code.




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


Open the app on the web browser in localhost and default port 8050.

http://127.0.0.1:8050/

Output:

Screenshot of the Basic Dash app.

Using Callbacks

The above teaches us a basic static app. But what if you want to let the user take the control. This is why we are going to use app callbacks provided in Dash. In this section, we are going to make a web app that takes in number from the user and return the square of the number

Step 1: Importing all the required libraries
Just like above we are going to import all the required libraries. Here we require an additional dash.dependencies.Input and dash.dependencies.Output to provide us with input and output callback functionality.




# importing required libraries
import dash
import dash_core_components as dcc    
import dash_html_components as html
from dash.dependencies import Input, Output 


Step 2: Designing a layout

We are going to design a simple textbox that will help out take input and a text label which will output the square of the number that is input or returns an error if the input is not a number.




app = dash.Dash()
  
app.layout = html.Div(children =[
    dcc.Input(id ='input'
              value ='Enter a number'
              type ='text'),
      
    html.Div(id ='output')
])


Step 3: Callbacks

A callback is like a trigger that does a certain function on the change of the state of the input. In this case, it executes the method update_value and takes in input_data as the parameter and returns the square of that number. If the input is not a number, then it returns an error statement.




@app.callback(
    Output(component_id ='output', component_property ='children'),
    [Input(component_id ='input', component_property ='value')]
)
  
def update_value(input_data):
    try:
        return str(float(input_data)**2)
    except:
        return "Error, the input is not a number"


Step 3: Running the server
Again, just like above, we are going to run the server.




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


Open the app on the web browser in local host and default port 8050.

http://127.0.0.1:8050/

Output:

Square of five using Python Dash callbacks.

Footnotes

The above two examples must be useful for you to understand the working of the Dash framework. Although the two examples written above might not be useful on itself, it does help in understanding the concepts of building web apps with Dash framework and that will help you in building a useful web app in the future using real data.



Previous Article
Next Article

Similar Reads

Plot Live Graphs using Python Dash and Plotly
Dash is a Python framework built on top of ReactJS, Plotly and Flask. It is used to create interactive web dashboards using just python. Live graphs are particularly necessary for certain applications such as medical tests, stock data, or basically for any kind of data that changes in a very short amount of time where it is not viable to reload eac
4 min read
Python | wxPython module Introduction
Python provides wxpython module which allows us to create high functional graphical user interface. It is an Open Source module, which means it is free for anyone to use and the source code is available for anyone to look and modify. It is implemented as a set of extension modules that wrap the GUI components of wxWidgets library which is written i
3 min read
Introduction and Installation of Uberi/Speechrecognition in Python
One of the best library for speech recognition in Python and uses various engines and API to perform speech recognition online as well as offline. Installation Use this command in cmd or terminal make sure Python is installed and Python path is also stored in pc. pip install speechrecognition OR Download resources from PyPI and extract it in a fold
2 min read
Introduction to Social Networks using NetworkX in Python
Prerequisite - Python Basics Ever wondered how the most popular social networking site Facebook works? How we are connected with friends using just Facebook? So, Facebook and other social networking sites work on a methodology called social networks. Social networking is used in mostly all social media sites such as Facebook, Instagram, and LinkedI
5 min read
Introduction to Altair in Python
Altair is a statistical visualization library in Python. It is a declarative in nature and is based on Vega and Vega-Lite visualization grammars. It is fast becoming the first choice of people looking for a quick and efficient way to visualize datasets. If you have used imperative visualization libraries like matplotlib, you will be able to rightly
5 min read
Introduction to Dynamic CLI in Python
In this article, we will see an introduction to Dynamic CLI in Python. What is Dynamic CLI? A Modern, user-friendly command-line HTTP client for API testing, It helps a programmer to code more efficiently by increasing one's productivity and by reducing the time and effort required to perform tasks of searching for solutions and making API requests
4 min read
An Introduction to Grammar of Graphics for Python
A grammar of graphics is basically a tool that enables us to describe the components of a given graphic. Basically, what this allows us to see beyond the named graphics, (scatter plot, to name one) and to basically see the underlying statistics behind it. The grammar of graphics was originally introduced by Leland Wilkinson in the 1990s and was pop
3 min read
BootStrap Introduction and Installation
To begin Web development you may go through this article first. Grid SystemButtons, Glyphicons, TablesVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive TabsProgress Bar and JumbotronBootstrap is a free and open-source collection of tools for creating websites and web applications. It is the most popular HTML, CSS, and JavaScrip
4 min read
Introduction to NumPy
This article will help you get acquainted with the widely used array-processing library NumPy in Python. What is NumPy? NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It is o
12 min read
Introduction to React Native
If you want to build mobile apps for both Android and iOS. What should you learn? The individual native languages for each app i.e, Java for Android and Swift/Objective-C for iOS?, Actually NO. Native Android and iOS development are quite different and can be expensive – first, the language itself is quite different, and second, all the underlying
3 min read
Practice Tags :