Pandas dash

Pandas dash DEFAULT

Develop and Deploy Interactive Dashboards Using Python Dash

Dash Introduction

Plotly has come up with a new framework called Dash which allows users to create interactive dashboards with visualizations capabilities powered by plotly express. Dash core components are used as building blocks for each application are quite exhaustive in terms of attributes. You can give a face to your Python application with it in no time.

Getting started with Dash

As an example we are building a simpledashboard to display IPL stats (runs scored, wickets taken) for each player through graphs. This will give you a basic understanding of applying Python dash framework which cloud be scaled further. You can download the IPL dataset from here.

You need to make sure that you have dash, plotly and pandas libraries installed in the machine. If not, you can simply do that by executing the below lines in command prompt after CD into the python installation folder or if you are working on Anaconda, just open the Anaconda prompt and execute the following lines.

pip install dash
pip install plotly
pip install pandas

Dash will be the most prominent of the 3 libraries as this will be instrumental in rendering the dashboard on the browser. Plotly will be used to create graphs. Lastly, we will use pandas for data manipulation.

Apart from this, you will also need very basic HTML and CSS which you can pick up on the go like me.

Creating the dashboard skeleton

Alright, let’s dive in then. Let’s first create our sections (HTML div) on the dashboard where we will place dash components for our app. We need one section for dash dropdown on the top and two parallel sections for displaying the dash graphs. In addition to this, we will encapsulate every section into one big section which will encompass our complete viewport.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from dash.dependencies import Input, Output
import plotly.express as pxapp = dash.Dash(__name__)
app.title = "IPL Dashboard"#Creating a section to place our dropdown
dropdown_box = html.Div(
children = ["dropdown", dcc.Dropdown()], #dash dropdown elementstyle = {'width': '90%', "position": "fixed", "left": "5%",
'display': 'inline-block', 'height':"5%", "top": "1%",
'z-index':'1', 'border': '2px solid green',
'text-align': 'center'}
)#Creating a section to place our graphs Graphs = html.Div(children = [
html.Div(children = ["Graph 1", dcc.Graph()], #dash graph elementstyle = {'width': '45%', "position": "fixed", "left": "2%",
'display': 'inline-block', 'text-align': 'center',
'top': '10%', 'border': '2px solid red', 'height':'50%'}
),html.Div(children = ["Graph 2", dcc.Graph()], #dash graph elementstyle = {'width': '45%', 'position': 'fixed', 'left': '53%',
'display': 'inline-block', 'text-align': 'center',
'top': '10%', 'border': '3px solid red', 'height':'50%'}
)])#creating and adding the main html div which encapsulates all elements on the viewportapp.layout = html.Div(id ="main_div", children=[input_box, Graphs],style = {'background-color': '#FFFFFF', 'padding':'0',
'width':'100%', 'height':'100%', 'position': 'fixed',
'top': '0%', 'left': '0%', 'bottom': '0%', 'height':'100%',
'border': '2px solid blue'}
)if __name__ == "__main__":
app.run_server(debug=False, port = 8080)

Adding interactivity to dashboard

Now that skeleton for dashboard is ready, let’s work on creating its soul to make it interactive. For that first we need to add an attribute to all our dash components. This will give each component a unique identifier which will be used to take input and display output on the dashboard. Apart from that we will use few more attributes which are available for dropdown like clearable, placeholder, value and options. You can look at all the attributes available for dash core components here.

To add interactivity dash offers a callback function that allows us to interact with components on the dashboard. The callback function takes input and throws output using the dash dependencies class. We can take multiple inputs from a dashboard using each dash component’s and attributes and similarly can render output using the same as well. We will see this in the code in detail. The limitation is — there can be only one callback function. However, we can call multiple functions inside this callback function.
Hence, we have defined two functions to render the plotly graphs. We will be calling these functions from our callback function.

So, now let’s look at how to apply the same in Python.

We have made a few changes from our skeleton version in the CSS to enhance the look and feel like removing the border, changing the background color etc.

Deploying the dashboard on the web:

There are multiple ways to deploy this dash app on the web. However, we selected Heroku for the same. For this, you need the below things.

1. Account on Git (Sign up).

2. Git bash installed on your machine.

3. Account on Heroku (Sign up)

4. Download Heroku CLI from here.

5. Optional yet helpful — Pycharm/Visual Studio installed on your computer.

Once you have set up the above resources follow the step-by-step process below.

  • Login to Heroku and click on - Create New App.
  • Give a name for your app and click - Create app.
  • Now, you need to create a new project in Pycharm/Visual Studio, in case you don’t have it, don’t worry. You just need to create one folder and place the files we will create in further steps in the folder.
  • Open the project path and add the file into the project folder. This file will contain all the Python code.
  • In your .py file under add this line:
  • Open terminal/command prompt, and CD into your project folder.
  • Pip install all libraries with specific versions your .py file needs to run.
pip install pandas==1.2.0
pip install plotly==4.8.0
pip install dash==1.12.0
pip install gunicorn==20.0.4 #Required to run app on Heroku.
  • Create a file in the project folder and name it .
  • Create a file in the project folder, name it and add this line to it

Go back to the terminal/command prompt and run the following commands.

  • pip freeze > requirements.txt
  • heroku login
  • git init
  • heroku git:remote -a yourHerokuAppName
  • git add .
  • git commit -am “initial launch”
  • git push heroku master

Congratulations!!! you have deployed your Dash app on the web. You can share the Heroku app URL to present the app to anyone. This offers an incredible solution to display reports or give an interface to your Python programs which users/clients can interact with.

Happy coding, have fun and stay healthy. And, in case you face any issues while applying it - I am just a comment away.

Sours: https://towardsdatascience.com/develop-and-deploy-interactive-dashboards-using-python-dash-66a7e4873429

Dash DataTable

User Guide

Reference

A comprehensive list of all of the DataTable properties.

DataTable Height

How to set the height of the DataTable. Examples include how to set the height with vertical scroll, pagination, virtualization, and fixed headers.

DataTable Width & Column Width

How to set the width of the table and the columns. Examples include how to handle word wrapping, cell clipping, horizontal scroll, fixed columns, and more.

Styling

The style of the DataTable is highly customizable. This chapter includes examples for:

  • Displaying multiple rows of headers
  • Text alignment
  • Styling the table as a list view
  • Changing the colors (including a dark theme!)

Conditional Formatting

Several examples of how to highlight certain cells, rows, or columns based on their value or state.

Number Formatting

Several examples of how to format and localize numbers.

Sorting, Filtering, Selecting, and Paging Natively

The DataTable is interactive. This chapter demonstrates the interactive features of the table and how to wire up these interations to Python callbacks. These actions include:

  • Paging
  • Selecting Rows
  • Sorting Columns
  • Filtering Data

DataTable Tooltips

Display tooltips on data and header rows, conditional tooltips, define tooltips for each cell, customize behavior.

Python-Driven Filtering, Paging, Sorting

In Part 3, the paging, sorting, and filtering was done entirely clientside (in the browser). This means that you need to load all of the data into the table up-front. If your data is large, then this can be prohibitively slow. In this chapter, you’ll learn how to write your own filtering, sorting, and paging backends in Python with Dash. We’ll do the data processing with Pandas but you could write your own routines with SQL or even generate the data on the fly!

Editable DataTable

The DataTable is editable. Like a spreadsheet, it can be used as an input for controlling models with a variable number of inputs. This chapter includes recipes for:

  • Determining which cell has changed
  • Filtering out null values
  • Adding or removing columns
  • Adding or removing rows
  • Ensuring that a minimum set of rows are visible
  • Running Python computations on certain columns or cells

Typing and User Input Processing

In this chapter, you’ll learn how to configure the table to

  • assign the column type
  • change the data presentation
  • change the data formatting
  • validate or coerce user data input
  • apply default behavior for valid and invalid data

Dropdowns Inside DataTable

Cells can be rendered as editable Dropdowns. This is our first stake in bringing a full typing system to the table. Rendering cells as dropdowns introduces some complexity in the markup and so there are a few limitations that you should be aware of.

Virtualization

Examples using DataTable virtualization.

Filtering Syntax

An explanation and examples of filtering syntax for both frontend and backend filtering in the DataTable.

Sours: https://dash.plotly.com/datatable
  1. Grey graph paper
  2. Chiropractor emmaus
  3. Hertz broadview
  4. Pomeranian dachshund mix

Python For Data Science — A Guide to Plotly Dash Interactive Visualizations

Click on the link to access your app.

and there you have it, your first ‘Hello World’ app.
That’s cool and all, but let’s show an actual graph in our app.

#initiating the app
app = dash.Dash()#defining the layout
app.layout = html.Div(children=[
html.H1(children='Hello World!')
html.Div(children='Dash: A web application framework for Python.'),dcc.Graph(
id='graphid',
figure={
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Cats'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': 'Dogs'},
],
'layout': {
'title': 'Cats vs Dogs'
}
}
)
])#running the app
if __name__ == '__main__':
app.run_server()

In this block of code, we introduced the Div tag ( one of the most used ) and the dcc.Graph component.

dcc.Graph component

The graph component is used to display a Plotly graph. The figure parameter is used to represent go.Figure, you can refresh your memory about it here.

fig = go.Figure(data = data,layout = layout)#data can be any type of plotly graphs (pie chart,scatter, etc)

Basically, you can pass any type of Plotly graph through the dcc.Graph component to be displayed on your app. You can then further customize the style of that graph in Plotly and Dash.

Now let’s make a layout for the data we have imported from Github.

app = dash.Dash()
df['year'] = random.randint(-4,5,len(df))*0.10 + df['model_year']app.layout = html.Div([
html.Div([
dcc.Graph(id='mpg-scatter',
figure={
'data':[go.Scatter(
x=df['year']+1900,
y=df['mpg'],
text=df['name'],
mode='markers'
)],
'layout':go.Layout(
title='MPG vs Model Year',
xaxis={'title':'Model Year'},
yaxis={'title':'MPG'},
hovermode='closest'
)}
)
],style={'width':'50%','display':'inline-block'}),
])if __name__ == '__main__':
app.run_server()

In this app, we are simply visualizing the miles per gallon against the model year of the vehicles in the dataset. On a side note, we can clearly see a slight increase in MPG as the model year of the vehicle increases.

Using the style parameter, we can declare how we want the graph to look in the dashboard. You can further drill down into the style by inspecting the element of the web app.

We can see that the width of this inner div is half of its parent div. This is because we had declared the following in our code.

style={'width':'50%'}

I think it’s pretty straight forward up till now, to make a simple dashboard in Dash we:

  • Plot the graphs as you would in Plotly
  • Insert the graphs as dcc.Graph components in Dash
  • Adjust the style according to our needs
  • Run the app

This is where it gets interesting.

After declaring our basic layout, Dash allows us to add complex interactions in our app. This component will also allow us to update our data, in real-time.

  • Make certain changes when users hover over your graph
  • Updates visualizations when users type something in a Search Bar
  • Updates data upon user refresh, or in real-time

Yes, you heard it right.
The dashboard will be able to update itself in real-time if required, but more on that later. Let’s talk about how callbacks can be used to update your data upon certain user actions.

Callback Functions

We achieve this by defining callback functions after the layout. Callback Functions, like any other functions, have —

  • an input
  • an output
  • what to do with the input
@app.callback(Output('<component-id>','<what to update>'),
[Input('<component-id>','<what to take in as Input>')])
def callback_graph(<random name for inputs>):
x = do something with x
return x

Using the component-ids we have declared in Dash, we are able to pinpoint exactly what do we want as an input for our function, and what to update as well.

Hoverdata

As an example, we will use a property that is included in the dcc.Graph component by default, ‘HoverData’. It returns a JSON string of information about the data you’re hovering over. Let me show you.

html.Div([
dcc.Markdown(id='hoverdata-text')
])@app.callback(Output('hoverdata-text','children'),
[Input('mpg-scatter','hoverData')])
def callback_stats(hoverData):
return str(hoverData)#children is the default property that a component will display

In this section, we’ve added a Div below the graph to show the content we are hovering over. As you can see, the content of the Div is updating instantly as we hover over different points in the graph. We achieve this by —

  • Taking HoverData as Input
  • Declaring the Div as output
  • Showing HoverData as plain text

*Extra Note: The pointIndex in the HoverData represents the Index of the DataFrame of the current data referenced. This will be useful later on.

That being said, we can do all sorts of stuff with the input we are taking in. The sky is the limit with this.

Back to Work

Let’s display something interesting about the dataset we had imported.
For our very first web app, we want to show for each data point —

  • Name of Car Model
  • Acceleration
  • Time taken to achieve 0 to 60 MPH

By taking advantage of the data in HoverData, we can refer to the actual data from our pandas dataframe, mpg.csv. We can then do calculations based on it and display all kinds of metrics we want to show.

I hope you realize by now, how powerful is the Dash Framework.

Sours: https://towardsdatascience.com/python-for-data-science-a-guide-to-plotly-dash-interactive-visualizations-66a5a6ecd93e
Introduction to Dash DataTable - Growing a Spreadsheet into an Application

.

Dash pandas

.

Introduction to Dash Plotly - Data Visualization in Python

.

You will also like:

.



927 928 929 930 931