Dash for python

Dash for python DEFAULT

Dash is a Python framework to build web applications specifically for interactive analytical dashboard or visualization (like pie chart, line plot etc.). It is open source and built on top of Plotly.js, React.js (for the JavaScript user interface) and Flask (for serving the pages).

I am dividing full basic dash tutorial into two parts:

1.    Build basic dash application structure

2.    Making interactive dash application (communication between two dashboards)

In this post I will cover first part where I will focus on how to learn basic dash with python by spending minimal amount of time. I will explain only those portions of dash framework which is required to understand whole Dash framework.By knowing those portion you can easily start developing web app in python using dash.

Note: Assuming you have prior basic knowledge in Plotly.How to plot dashboard using Plotly kind of knowledge I am expecting.

Also Read:

Prerequisites and installations

While writing codes for this post I had below software and package versions:

  • Python Version: 3.6.3
  • Dash Version: 1.7.0

You can install dash by typing below command in cmd:

pip install dash

Applicationstructure of Dash with python

So now let’s first make our first dash app and then I will explain its structure.

Note: I am writing this application in a notepad++/ Sublime Text (not Jupyter notebook). To run this application type below command in cmd inside particular directory: 

python code_name.py.

## 1st Example Application: Basic
import dash
import dash_core_components as dcc
import dash_html_components as html

# Read plotly example dataframe to plot barchart
import plotly.express as px
df = px.data.gapminder().query("country=='India'")

# Start Application
app = dash.Dash()
# Define application window name/ title
app.title = 'FirstApp'

# Application Layout
app.layout = html.Div(
html.Div([
html.H1(children='First Dash Application: Indian Population over time'),
html.H3(children='Indian Population over time'),
html.Div(children='Dash: Python framework to build web application'),

dcc.Graph(
id='bar-chart',
figure={
'data': [
{'x': df['year'], 'y': df['pop'], 'type': 'bar', 'name': 'SF'},
],
'layout': {
'title': 'Bar Chart Visualization'
}
}
),

])
)

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

Now open any browser, your plots will be visible at below link:

Default link for dash web application:

http://127.0.0.1:8050/

The application should look like below. You can hover to the plot to view the value. In this application I am trying to visualize Indian Population over the years.

Now let’s understand the code in detail. We can divide above code into four parts like below:

1.    Import packages: Import all required packages

2.    Python coding/ Function: In this portion you can write any python codes or functions required to manipulate data or anything. You can say backend/ server side portion of the application.

3.    Dash Application Layout: This is the dash frontend application design portion. Here you can style and arrange your application page with different dashboard, table or anything you want at frontend portion of your dash application by using different type of html componentsand dash core components (dcc).

4.    Calling Dash Application:This portion needs to be written at the end of the code to run dash application in flash local hosted server. 

Hope you understand application structure of Dash Application using Python.Now above application have only one dashboard. Now we should know how to add multiple plots/ dashboards in dash application.

Multiple plots in dash application with Python

## 2nd Example Application: Multiple App
import dash
import dash_core_components as dcc
import dash_html_components as html

# Read plotly example dataframe to plot barchart
import plotly.express as px
df = px.data.gapminder().query("country=='India'")

app = dash.Dash()
app.title = 'MultipleApp'

app.layout = html.Div(
html.Div([
html.H1(children='Multiple Application: Indian Population over time'),
html.H3(children='Indian Population over time'),
html.Div(children='Dash: Python framework to build web application'),

dcc.Graph(
id='bar-chart',
figure={
'data': [
{'x': df['year'], 'y': df['pop'], 'type': 'bar', 'name': 'SF'},
],
'layout': {
'title': 'Bar Chart Visualization'
}
}
),

# Adding one more app/component

dcc.Graph(
id='line-chart',
figure={
'data': [
{'x': df['year'], 'y': df['pop'], 'type': 'line', 'name': 'SF'},
],
'layout': {
'title': 'Line Chart Visualization'
}
}
)

])
)

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

In this application I am trying to visualize Indian Population over the years by using bar chart and line chart.

Now let’s have a look into only those parts of this code where I made changes to plot single to multiple visualizations.

Changes are listed below:

1.    Added one more dash core component (line chart)

2.    Changed the server port to 8051 (default is: 8050). So now your application link for multiple application is http://127.0.0.1:8051/ 

But as you can see two plots are appearing one after one (row wise) in the page. Now let’s see how to showcase multiple plots column wise or side by side in dash with python. You can even divide your entire webpage into so many parts (row wise or column wise) by using bootstrap.

Bootstrap in Dash with Python

In this part I will show you by using bootstrap how you can arrange your entire webpage developed by using Dash.

What is Bootstrap?

Bootstrap is a CSS Framework to develop responsive websites. By using bootstrap/ CSS you can arrange/ style your entire webpage and make it responsive (works properly for different screen size).

Let me explain the architecture of bootstrap I have used for this tutorial.

Row: To divide page into multiple rows. Total number of row can be anything

Column: To split page into multiple columns. Total number of column should be 12 to fit everything properly.

Image source

So let’s see how our code and output will look like if we are using bootstrap in Dash.

## 3rd Example Application: Bootstrap
import dash
import dash_core_components as dcc
import dash_html_components as html

# Read plotly example dataframe to plot barchart
import plotly.express as px
df = px.data.gapminder().query("country=='India'")
# Define Dash app with extarnal style sheet (bootstrap)
app = dash.Dash(external_stylesheets=['https://codepen.io/amyoshino/pen/jzXypZ.css'])
app.title = 'MultipleColumn'

app.layout = html.Div(
html.Div([
# Adding one extar Div
html.Div([
html.H1(children='Multiple Application'),
html.H3(children='Indian Population over time'),
html.Div(children='Dash: Python framework to build web application'),
], className = 'row'),

html.Div([
html.Div([
dcc.Graph(
id='bar-chart',
figure={
'data': [
{'x': df['year'], 'y': df['pop'], 'type': 'bar', 'name': 'SF'},
],
'layout': {
'title': 'Bar Chart Visualization'
}
}
),
], className = 'six columns'),

# Adding one more app/component
html.Div([
dcc.Graph(
id='line-chart',
figure={
'data': [
{'x': df['year'], 'y': df['pop'], 'type': 'line', 'name': 'SF'},
],
'layout': {
'title': 'Line Chart Visualization'
}
}
)
], className = 'six columns')

], className = 'row')
])
)

if __name__ == '__main__':
app.run_server(8052, debug=False)

Now here you can see two plots are coming side by side (horizontally) instead of one by one vertically. This is the effect of bootstrap or css.

Dash Bootstrap Code explanation

To arrange entire page like above I have added some lines to previous code, which is marked in red lines or box. Changes are listed below.

1.    Divided each section of the entire page by html.Div which is a html component of dash.

2.    Inserted css/ bootstrap class name at the end of each html.Div component.

I have divided entire page into

1.    Two rows: One for heading of the page and another for plotting section

2.    Now plotting section further divided into two columns.

Note: One extra thing you can observe is id. Id is nothing but id of a div element. It is required to make any plot interactive, which I will cover in my next article.

Also Read:

Conclusion

In this tutorial you learned

  • What is dash framework in python?
  • How to make dash application or dashboard
  • How to plot multiple dashboards in one page by using dash with python
  • How to arrange multiple plot in dash using bootstrap css

If you have any question or suggestion regarding this topic see you in comment section. I will try my best to answer.

Sours: https://thinkinfi.com/learn-dash-with-python-in-5-minutes/

Python Dash vs. R Shiny – Which To Choose in 2021 and Beyond

Developing dashboards is no small task. You have to think about a vast amount of technical details and at the same time build something easy and enjoyable to use. Let’s say you have those areas covered. The question remains – which technology should you use? R or Python? 

Today we’ll compare two technologies for building web applications – Python Dash and R Shiny. After reading this article, you’ll know how these two compare and when it’s better to use one over the other. You’ll also see if it’s worth it to make a long-term switch to either. For a truly immersive face-off experience, download the source code of the sample dashboard used to illustrate Dash and Shiny capabilities.

Introduction

At Appsilon, we are global leaders in R Shiny and we’ve developed some of the world’s most advanced R Shiny dashboards, so we have a natural bias towards using Shiny. Still, we’ll do our best to provide an honest and unbiased opinion in this article. We’re not going to throw arbitrary points to Shiny just because we prefer it for enterprise app development.

It’s also worth noting that whether you choose Dash or Shiny (or both!), you can deploy your apps through RStudio Connect. With Connect, you can now share Flask APIs and interactive dashboards written in both R and Python. Appsilon is a Full-Service Certified RStudio Partner and can assist with deployment and app scaling regardless of your choice of underlying technology.

Library Overview

Let’s start with Dash. It is a Python framework used for building web applications. It’s written in Flask, Plotly.js, and React.js, so it’s an ideal candidate for creating dashboards. If you’re a heavy Python user, Dash will allow you to express your analysis quickly and visually.

Here’s an example dashboard you can create with Dash:

New York Uber Rides Dash Dashboard

New York Uber rides Dash dashboard

Want to see more dashboard examples? Check out Plotly’s official app gallery.

On the other hand, R Shiny is an open-source package for building web applications with R. It provides a robust web framework for developing any sort of apps, not only dashboards. Shiny is easy and intuitive to use, as you’ll see in the examples below. It also doesn’t require any HTML, CSS, or JavaScript knowledge – but this is helpful if you want extra customizability.

Here’s an example dashboard you can create with Shiny:

Shiny Enterprise Dashboard

Shiny Enterprise Dashboard

Winner: Tie. You can develop identical solutions with both Dash and Shiny.

Boilerplate Comparison

Every web framework comes with a chunk of code needed for the application to run. You can’t avoid writing this code, or at least copying it from a previous project. That’s called boilerplate code. This section will show you just how much code is needed to start a Dash and a Shiny application. You will create two identical applications by the end, each showing only a single H3. Let’s begin with Dash.

Here’s the corresponding application:

Basic Dash application

Basic Dash application

So eleven lines in total, and you haven’t imported any data visualization library. Three lines are empty – used for formatting purposes. In general – not bad. Let’s see what’s the deal with Shiny:

Only nine lines here, of which three are empty. Here’s the corresponding application:

Basic Shiny application

Basic Shiny application

Winner: R Shiny. Does it really matter much, though? It’s only boilerplate code, after all. At this initial stage – no, it seems like it doesn’t matter. However, for more advanced applications, Dash requires a lot more boilerplate code than Shiny does. For instance, there are no reactive intermediate variables with Dash, which is a big drawback. We’ll return to this theme of Shiny ease-of-use throughout the article.

Creating UI Elements

Let’s continue our comparison by taking a look at UI elements. The goal is to create the same form-based application in both Dash and Shiny. The application should be used to filter job candidates by level, skills, and experience. It also allows you to specify additional points of interest.

Let’s start with Python’s Dash. All of the core UI components are available in the library. The convention is to import it abbreviated as . Other imports and boilerplate remain the same. 

Here’s the code for a simple form-based application:

And here’s the corresponding application:

Simple form-based application in Python's Dash

Simple form-based application in Python Dash

Yeah, not the prettiest. Dash doesn’t include too many styles by default, so you’ll have to do it independently. 

Let’s replicate the same application with R and Shiny:

Here’s the corresponding application:

Simple form-based application in R Shiny

Simple form-based application in R Shiny

As you can see, Shiny includes a ton more styling straight out of the box. Shiny applications look better than Dash applications by default. However, who wants their apps to look “default” anyway? We’ll cover custom styling in the next section.

Winner: R Shiny. You can create a better-looking application with less code.

Styling UI with Custom CSS

Nobody likes a generic-looking application. The aesthetics of your app are tied directly with how users feel about it. With advancements in design, we’re used to commercial apps looking spectacular. That doesn’t mean developing great-looking apps is easy, especially for developers.

Still, adding a touch of style through CSS is more or less a must for your app. This section compares how easy it is to add styles to both Dash and Shiny if the same stylesheets look identical across the two. Who knows, maybe default stylings on Shiny will come as a drawback. Later, we’ll compare how easy it is to add custom CSS frameworks like Boostrap to your app.

A CSS file for the Dash application goes to the folder and in the folder for Shiny apps. Create these folders in a root directory, where your application file is. 

Here’s the complete CSS for both Dash and Shiny – called :

Let’s now use it to create a simple styled application – first with Dash:

Here’s the corresponding application:

Styled Dash application

Styled Dash application

As you can see, the stylings work just as for any regular web application. That’s because Dash didn’t add its default styles like Shiny did.

Here’s the code for a styled R Shiny app:

And here’s the corresponding dashboard:

Styled Shiny application

Image 8 – Styled Shiny application

Well, that obviously doesn’t look right. The more elaborate default Shiny styling is conflicting with our custom styling. Shiny needs a bit more work with stylings than Dash, but that’s something you can quickly get used to. Still, the included styling with default Shiny apps means that there is a bit more work required to add custom styling to a Shiny app than a Dash app at a basic level.

Winner: Dash. This doesn’t mean you can’t make Shiny apps look fantastic, though.

Styling UI with Bootstrap

Let’s discuss CSS frameworks. Bootstrap’s been one of the most popular frameworks for years, so naturally, you might want to include it in your apps. It’s a great way to introduce new design elements and give your apps a fresher look. Your apps will still look kind of “default” – that’s mostly because Bootstrap has been out for so long and we’ve come to associate it with a “standard” appearance. Anyone who has been in web design/development for more than a short period knows this to be true.

Including Bootstrap in Dash is easy. You just have to install the library and you’re good to go. The code below shows you how to create a navigation bar and a jumbotron in Dash:

Here’s the corresponding application:

Dash and Bootstrap

Dash and Bootstrap

R Shiny is different. It comes with Bootstrap out of the box, but not with the most recent version. Bootstrap version 4.5 is the latest at this point, but Shiny is still stuck on 3.3.5. One solution for addressing this issue is by using the library. Here’s how to make the same application with Shiny:

Shiny and Bootstrap

Shiny and Bootstrap

As you can see, it is a code-heavy solution. It requires you to specify every CSS class and other properties as if you were writing in pure HTML. Declaring a winner in this department is a no-brainer.

Winner: Dash. Using Bootstrap is much cleaner in Dash than in Shiny.

Reactivity

Dashboards shouldn’t look and behave like plain reports. They have to be interactive. Users won’t like your dashboards if they can’t easily change what’s displayed and even interact with individual data points. That’s where reactivity (or callbacks) comes in. Options are endless here. You can update every component as a single input changes, update only selected components, delay updates until the button is pressed, etc. We’ll stick to the basics and perform the update when any of the inputs change.

For our example, you’ll have a single text input and two dropdown menus. Their values determine how the visualization looks. The text input is used to change the title, and the two dropdowns are used for attributes shown on the X and Y axes.

Let’s start with Python and Dash. Here’s the code:

And here’s the corresponding dashboard:

Reactivity demonstration with Python and Dash

Reactivity demonstration with Python Dash

It’s a simple dashboard but requires a fair amount of code. Nevertheless, the code is simple to read and understand. Dash uses `@app.callback` decorator pattern to handle reactivity. You can update as many components in a single callback and get values from as many components as needed.

R Shiny is a bit simpler. It requires significantly less code to produce the same output. Still, the syntax might look strange if you’re not used to R (e.g., double exclamation point in front of column names). 

Here’s the code for producing the identical dashboard:

Here’s the corresponding dashboard:

Reactivity demonstration with R Shiny

Reactivity demonstration with R Shiny

Winner: R Shiny. Shiny requires less code than Dash for better-looking output.

Python Dash vs. R Shiny: final face-off

The final results are in:

  • R Shiny – 3 points
  • Python Dash – 2 points
  • Tie – 1 point

It looks like R shiny is ahead by a single point. Does this mean that R Shiny is better for everyone and every scenario? Absolutely not. You can develop identical production-ready applications in both technologies. What you choose depends on your specific needs and preferences.

R Shiny is a bit faster for developers. It requires less code than Dash for identical solutions. That’s if you decide to not use Bootstrap in your dashboards. Further, creating custom components in Dash requires extensive React.js knowledge, which is a large hurdle. Dash also falls short with intermediate reactive variables. Using them requires you to create a hidden div to store and reuse calculations. An alternative solution exists, but it’s still a big drawback when compared to R Shiny.

What else can you do with Shiny? Check out our free Shiny dashboard templates.

If you need to create powerful, customizable, and interactive dashboards that look great and respond to user input, Shiny is a clear choice. It requires a bit of coding knowledge even for simple dashboards, but R isn’t a very complicated language. You can quickly get up to speed in a couple of weeks or even a couple of days, depending on your prior knowledge of programming. If you want to make a scalable enterprise Shiny dashboard, then you can always reach out to Appsilon for help. We’re continuously pushing the limits of what’s possible with Shiny, and we’d be happy to guide you and your company.

Learn More

 

Appsilon is hiring globally! See our Careers page for all new openings.



Reach out to Appsilon

Maria Grycuk

Maria Grycuk

Project Manager

Reach out to Appsilon

Maria Grycuk

Maria Grycuk

Project Manager

Sours: https://appsilon.com/dash-vs-shiny/
  1. Nether diamond
  2. Brown plastic tarps
  3. Az sidewinders

Build a Dash app with Python in 7 minutes

Tutorials

Create a beautiful visualization app with Python from scratch

  • Natassha
Build a Dash app with Python in 7 minutes

When I started working on my capstone project a few months ago, I wanted to create an interactive dashboard for my machine learning model.

I wanted this dashboard to be in the form of a web application and display live updates as new data entered the system.

After exploring many visualization tools, I decided to go with Dash.

Dash is an open-source library that allows you to create interactive web applications in Python.

If you use Python regularly to build data visualizations, Dash is the perfect tool for you. You can create a GUI around your data analysis and allow users to play around with your dashboard application.

The best thing about Dash is that it allows you to build these things purely in Python. You can create web components without having to write any HTML or Javascript code.


In this tutorial, I will show you how to create a simple data visualization application with Dash.

The end product will look like this:


Step 1: Pre-requisites

Before we start building the app, you will need to have:

  • A Python IDE: I'm using Visual Studio Code for this analysis, but any Python IDE will work (Except for Jupyter Notebooks).
  • Libraries: Install Dash, Pycountry, Plotly, and Pandas
  • Data: I used the Zomato Kaggle Dataset to build the web app. I made some changes to the dataset to make it suitable for this analysis, and you can find the pre-processed version here.

Step 2: Building the Dashboard

First, let's import all the necessary libraries to build the app:

If the above lines of code execute successfully, great job! All the installations worked.

Just below the imports, add this line of code to include a CSS stylesheet in your Dash app:

Then, let's initialize Dash:

Now, we can read the data frame into Pandas with the following lines of code:

The head of the data frame looks like this:

This data frame consists of restaurant data - the name of each restaurant, their location, rating, and popularity.

We will visualize some of this data on our Dash app.

We will create three charts to display on our Dash app - a map, a bar chart, and a pie chart.

Let's start with the map.

We will visualize the number of restaurants present in the dataset by country. The end product will look like this:

We will be using the 'country_iso' column in the dataset to do this. We need to count the number of restaurants in for each country and create a new 'count' column, which can be done with the following lines of code:

Great! Now, we can create the map with the 'country_iso' and 'count' columns:

The above lines of code will create the map, and colour each region according to the number of restaurants listed.

Now, we can start creating the bar chart.

If you look at the map displayed above, India has the highest number of restaurants in the data frame. 8,155 restaurants listed in the data frame are in India.

Let's take a look at the most popular restaurants in India with the following lines of code:

The codes above will render a bar chart that looks like this:

(Note that you won't be able to run the codes yet until you finish creating and displaying all the components)

Let's create the final chart.

We will look at the overall rating distribution in the dataset:

The pie chart created by the codes above will look like this:

Now that we're done creating all three charts, let's display them on the web page and run the Dash app.

We first need to come up with the page layout and structure of our web app.

The Dash components follow a grid structure (similar to CSS grid layout). Dash has three core components - rows, columns, and containers.

You can arrange these components in any way to like to fit your elements on the page.

Since we only have three charts, I came up with this simple layout:

We will only use two rows for these charts, and the second row will have two columns to accommodate the bar and pie chart.

Here is some code to create a layout like this in Dash:

All we need to do now is define our app layout and run the server:

By default, Dash runs on port 8050. If this is in use, you can manually specify the port you want to run it on.


We're done coding the dashboard application.

Just run the Python app and navigate to the dashboard location, and you will see your visualizations:


Here is the complete code for this Dash project:


You can play around with the code and try changing the colours and layout of the charts. You can even try creating new rows and adding more charts using the dataset above.

Dash has many more functionalities than I touched on in this tutorial. You can create filters, cards, and add live updating data. If you enjoyed this tutorial, I'll write another one covering more features and functionalities of Dash.

Thanks for reading, and have a great day :)

Sours: https://www.natasshaselvaraj.com/interactive-dashboard-python/
Python Interactive Dashboards with Plotly Dash - Quick Tutorial

Dash

CircleCIGitHubPyPIPyPI - Python VersionGitHub commit activityLGTM AlertsLGTM Grade

Dash is the most downloaded, trusted Python framework for building ML & data science web apps.

Built on top of Plotly.js, React and Flask, Dash ties modern UI elements like dropdowns, sliders, and graphs directly to your analytical Python code. Read our tutorial (proudly crafted with Dash itself).

  • Docs: Create your first Dash app in under 5 minutes

  • dash.gallery: Dash app gallery with Python & R code

Dash App Examples

To learn more about Dash, read the extensive announcement letter or jump in with the user guide.

Dash OSS & Dash Enterprise

With Dash Open Source, Dash apps run on your local laptop or workstation, but cannot be easily accessed by others in your organization.

Scale up with Dash Enterprise when your Dash app is ready for department or company-wide consumption. Or, launch your initiative with Dash Enterprise from the start to unlock developer productivity gains and hands-on acceleration from Plotly's team.

ML Ops Features: A one-stop shop for ML Ops: Horizontally scalable hosting, deployment, and authentication for your Dash apps. No IT or DevOps required.

  • App manager Deploy & manage Dash apps without needing IT or a DevOps team. App Manager gives you point & click control over all aspects of your Dash deployments.
  • Kubernetes scaling Ensure high availability of Dash apps and scale horizontally with Dash Enterprise’s Kubernetes architecture. No IT or Helm required.
  • No code auth Control Dash app access in a few clicks. Dash Enterprise supports LDAP, AD, PKI, Okta, SAML, OpenID Connect, OAuth, SSO, and simple email authentication.
  • Job Queue The Job Queue is the key to building scalable Dash apps. Move heavy computation from synchronous Dash callbacks to the Job Queue for asynchronous background processing.

Low-Code Features: Low-code Dash app capabilities that supercharge developer productivity.

  • Design Kit Design like a pro without writing a line of CSS. Easily arrange, style, brand, and customize your Dash apps.
  • Snapshot Engine Save & share Dash app views as links or PDFs. Or, run a Python job through Dash and have Snapshot Engine email a report when the job is done.
  • Dashboard Toolkit Drag & drop layouts, chart editing, and crossfilter for your Dash apps.
  • Embedding Natively embed Dash apps in an existing web application or website without the use of IFrames.

Enterprise AI Features: Everything that your data science team needs to rapidly deliver AI/ML research and business initiatives.

  • AI App Marketplace Dash Enterprise ships with dozens of Dash app templates for business problems where AI/ML is having the greatest impact.
  • Big Data for Pything Connect to Python's most popular big data back ends: Dask, Databricks, NVIDIA RAPIDS, Snowflake, Postgres, Vaex, and more.
  • GPU & Dask Acceleration Dash Enterprise puts Python’s most popular HPC stack for GPU and parallel CPU computing in the hands of business users.
  • Data Science Workspaces Be productive from Day 1. Write and execute Python, R, & Julia code from Dash Enterprise's onboard code editor.

See https://plotly.com/contact-us/ to get in touch.

image

Sours: https://github.com/plotly/dash

Python dash for

Introduction to Dash

Dash is a productive Python framework for building web analytic applications.

Written on top of Flask, Plotly.js, and React.js,
Dash is ideal for building data visualization apps
with highly custom user interfaces in pure Python.
It’s particularly suited for anyone who works with data in Python.

Through a couple of simple patterns, Dash abstracts away all of the
technologies and protocols that are required to build an
interactive web-based application.
Dash is simple enough that you can bind a user interface
around your Python code in an afternoon.

Dash apps are rendered in the web browser. You can deploy your apps
to servers and then share them through URLs.
Since Dash apps are viewed in the web browser, Dash is inherently
cross-platform and mobile ready.

There is a lot behind the framework. To learn more about how it is built
and what motivated Dash, watch our talk from
Plotcon below
or read our announcement letter.

Dash is an open source library, released under the permissive MIT license.
Plotly develops Dash and offers a
platform for managing Dash apps in an enterprise environment.

Sours: https://dash-docs.herokuapp.com/introduction
Python Interactive Dashboards with Plotly Dash - Quick Tutorial

Introduction to Dash in Python

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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., )

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

 

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.

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.

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.

 

 

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.

 

Step 3: Running the server
Again, just like above, we are going to run the 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.




Sours: https://www.geeksforgeeks.org/introduction-to-dash-in-python/

Similar news:

Dash for Beginners : Python Dashboards

Python interactive dashboards using plotly dash

Want to learn plotly Dash ? Read the following article to get a basic understanding of plotly Dash. Get an in-depth understanding by either following the official documentation or check out my course on Udemy where you will learn how to create full fledged interactive dashboard. Use the following link to get upto 60% off : https://bit.ly/3iFGJTQ

Dash is a python framework created by plotly for creating interactive web applications. Dash is written on the top of Flask, Plotly.js and React.js. With Dash, you don’t have to learn HTML, CSS and Javascript in order to create interactive dashboards, you only need python. Dash is open source and the application build using this framework are viewed on the web browser.

With Dash, you don’t have to learn HTML, CSS and Javascript in order to create interactive dashboards, you only need python.

Dash applications are made up of 2 building blocks :

  1. Layout
  2. Callbacks

Layout describes the look and feel of the app, it defines the elements such as graphs, dropdowns etc and the placement, size, color etc of these elements. Dash contains Dash HTML components using which we can create and style HTML content such as headings, paragraph, images etc using python. Elements such as graphs, dropdowns, sliders are created using Dash Core components.

Callbacks are used to bring interactivity to the dash applications. These are the functions using which, for example, we can define the activity that would happen on clicking a button or a dropdown.

Now, let’s have a look at how we can create web based layouts using plotly Dash. Before starting with the layout, let’s install some required packages.

Now, we will import dash package, dash_html_components for HTML classes, dash_core_components for elements such as graph, dropdown etc, and plotly packages for creating plots and reading stock prices dataset.

(In the below code) We are initializing our dash app using dash package. Then, we are reading the stock prices data for different companies from 2018 to 2019. We are creating stock_prices function that returns the line chart for Google’s stock prices.

(In the above code) At line 16, we are setting our layout using html Div component, which is a kind of wrapper within which the elements(heading, graph) of the layout will be created. The Div component contains arguments such as id (a unique identifier of the element), style (for setting the width, height, color etc) and children (equal to square bracket within which elements of the layout are initialised).

Inside the children component (of html.Div) we are creating html H1 heading at line 17 using H1 function. Inside the function, we are setting the unique id of the function (id = ‘H1’), children property using which we set the text of the heading and style property as a dictionary within which we are setting styling such as center aligning the text, setting top and bottom margin to 40 pixel. At line 21, we are using dash core component (dcc) to create graph , where we are setting the id of the graph and the figure argument, which is equal to the function call (stock_pricest()) that returns the plotly figure object.

In order to view our application, we need to run our web server just like in Flask. Remember Dash is built on top of Flask.

On running the app, you will see that the app is running on http://127.0.0.1:8050/ , which is your local server. Copy this url and paste it in your browser and you will see the below vizualisation.

Now, we will create a dropdown using dash core components. Using the dropdown, we will be able to select the stocks of Google, Apple or Amazon.

Dropdowns are created using the Dropdown() function, which has the following arguments -

  1. id — Unique identifier of the dropdown.
  2. options — Sets the ‘label’ (the text visible in the dropdown) and ‘value’ (used by dash to communicate with callbacks) as key value pair.
  3. value — default selection for the dropdown.

Now, let’s have a look at how we can create the callback that will connect the dropdown and the stock prices line chart.

A callback is initialised using @app.callback(), which is followed by a function definition. Within this function, we define what happens on changing the value of the dropdown.

Let’s have a look at the arguments within the callback function :

  1. Output: This is used to define the components within the layout which will be updated when the function below the callback (graph_update()) return some object. Output function takes 2 arguments — 1) component_id defines the id of the component we want to update with our function graph_update. We want to update stock prices chart within the dcc.Graph, so we will set the component id to ‘line_plot’, which is id of our graph component. 2) Component property defines the property of the component that will be updated, which is figure property of dcc.Graph in our layout.
  2. Input: This is used to define the components, the change in whose value will trigger the callback. Input function also takes component_id and component_property as argument. We want the callback to get triggered based on change in the value of our dropdown, so we set the component_property to ‘value’ property of dropdown. Please note that Input is defined within a list.

The component property of Input function, which is ‘value’ of the dropdown, goes as an argument within the function graph_update. Inside the function we are creating scatter plot and returning the figure object fig, which is passed to the figure property of dcc.Graph using the Output function of the callback.

Now let’s combine the layout, the dropdown and the callback in the below code :

The image below shows how the change in the value of dropdown updates our stock prices line chart.

So, we looked at how we can create interactive dashboards using plotly Dash. Firstly, we created the layout using html components and dash core components. Then, we added dropdown and connected it with the stock prices line chart using callback.

Want to learn more about plotly Dash ? Either you can follow the official documentation or check out my course on Udemy where you will learn how to create full fledged interactive dashboard. Use the following link to get upto 60% off : https://bit.ly/3iFGJTQ

Sours: https://towardsdatascience.com/dash-for-beginners-create-interactive-python-dashboards-338bfcb6ffa4


1478 1479 1480 1481 1482