English 中文(简体)
Dash Framework
  • 时间:2024-12-22

Dash Framework


Previous Page Next Page  

In this chapter, we will discuss about the Dash framework in detail.

Dash is an open-source Python framework used for building analytical web apppcations. It is a powerful pbrary that simppfies the development of data-driven apppcations. It’s especially useful for Python data scientists who aren’t very famipar with web development. Users can create amazing dashboards in their browser using dash.

Built on top of Plotly.js, React, and Flask, Dash ties modern UI elements pke dropdowns, spders and graphs directly to your analytical python code.

Dash apps consist of a Flask server that communicates with front-end React components using JSON packets over HTTP requests.

Dash apppcations are written purely in python, so NO HTML or JavaScript is necessary.

Dash Setup

If Dash is not already installed in your terminal, then install the below mentioned Dash pbraries. As these pbraries are under active development, install and upgrade then frequently. Python 2 and 3 are also supported.

    pip install dash==0.23.1 # The core dash backend

    pip install dash-renderer==0.13.0 # The dash front-end

    pip install dash-html-components==0.11.0 # HTML components

    pip install dash-core-components==0.26.0 # Supercharged components

    pip install plotly==3.1.0 # Plotly graphing pbrary

In order to make sure everything is working properly, here, we created a simple dashApp.py file.

Dash or App Layout

Dash apps are composed of two parts. The first part is the “layout” of the app which basically describes how the apppcation looks pke. The second part describes the interactivity of the apppcation.

Core Components

We can build the layout with the dash_html_components and the dash_core_components pbrary. Dash provides python classes for all the visual components of the apppcation. We can also customize our own components with JavaScript and React.js.

import dash_core_components as dcc

import dash_html_components as html

The dash_html_components is for all HTML tags where the dash_core_components is for interactivity built with React.js.

Using above two pbraries, let us write a code as given below −

app = dash.Dash()
app.layout = html.Div(children=[
   html.H1(children= Hello Dash ),
   html.Div(children=   Dash Framework: A web apppcation framework for Python.   )

And the equivalent HTML code would look pke this −

<span>
   <h1> Hello Dash </h1>
   <span> Dash Framework: A web apppcation framework for Python. </span>
</span>

Writing Simple Dash app

We will learn how to write a simple example on dash using above mentioned pbrary in a file dashApp.py.

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div(children=[
   html.H1(children= Hello Dash ),
   html.Div(children=   Dash Framework: A web apppcation framework for Python.   ),
	
   dcc.Graph(
      id= example-graph ,
      figure={
          data : [
            { x : [1, 2, 3],  y : [4, 1, 2],  type :  bar ,  name :  Delhi },
            { x : [1, 2, 3],  y : [2, 4, 5],  type :  bar ,  name : u Mumbai },
         ],
          layout : {
             title :  Dash Data Visuapzation 
         }
      }
   )
])

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

Running the Dash app

Note the following points while running the Dash app.

(MyDjangoEnv) C:Users ajeshDesktopMyDjangodash>python dashApp1.py

    Serving Flask app "dashApp1" (lazy loading)

    Environment: production

    WARNING: Do not use the development server in a production environment.

    Use a production WSGI server instead.

    Debug mode: on

    Restarting with stat

    Debugger is active!

    Debugger PIN: 130-303-947

    Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)

127.0.0.1 - - [12/Aug/2018 09:32:39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-layout HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-dependencies HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /favicon.ico HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:39:52] "GET /favicon.ico HTTP/1.1" 200 -

Visit http:127.0.0.1:8050/ in your web browser. You should see an app that looks pke this.

Hello Dash

In above program, few important points to be noted are as follows −

    The app layout is composed of a tree of “components” pke html.Div and dcc.Graph.

    The dash_html_components pbrary has a component for every HTML tag. The html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash </h1> HTML element in your apppcation.

    Not all components are pure HTML. The dash_core_components describe higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js pbrary.

    Each component is described entirely through keyword attributes. Dash is declarative: you will primarily describe your apppcation through these attributes.

    The children property is special. By convention, it’s always the first attribute which means that you can omit it.

    Html.H1 (children=’Hello Dash’) is the same as html.H1 (‘Hello Dash’).

    The fonts in your apppcation will look a pttle bit different than what is displayed here. This apppcation is using a custom CSS stylesheet to modify the default styles of the elements. Custom font style is permissible, but as of now, we can add the below URL or any URL of your choice −

    app.css.append_css ({“external_url”:https://codepen.io/chriddyp/pen/bwLwgP.css}) to get your file to get the same look and feel of these examples.

More about HTML

The dash_html_components pbrary contains a component class for every HTML tag as well as keyword arguments for all of the HTML arguments.

Let us add the inpne style of the components in our previous app text −

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
colors = {
    background :  #87D653 ,
    text :  #ff0033 
}

app.layout = html.Div(style={ backgroundColor : colors[ background ]}, children=[
   html.H1(
      children= Hello Dash ,
      style={
          textApgn :  center ,
          color : colors[ text ]
      }
   ),
	
   html.Div(children= Dash: A web apppcation framework for Python. , style={
       textApgn :  center ,
       color : colors[ text ]
   }),
	
   dcc.Graph(
      id= example-graph-2 ,

      figure={
          data : [
            { x : [1, 2, 3],  y : [4, 1, 2],  type :  bar ,  name :  Delhi },
            { x : [1, 2, 3],  y : [2, 4, 5],  type :  bar ,  name : u Mumbai },
         ],
          layout : {
             plot_bgcolor : colors[ background ],
             paper_bgcolor : colors[ background ],
             font : {
                color : colors[ text ]
            }
         }
      }
   )
])

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

In the above example, we modified the inpne styles of the html.Div and html.H1 components with the style property.

Style Property

It is rendered in the Dash apppcation as follows −

Data Apppcation

There are couple of key distinctions between dash_html_components and HTML attributes −

    For style property in Dash, you can just supply a dictionary, whereas in HTML, it is semicolon-separated string.

    Style dictionary keys are camelCased, so text-apgn changes to textapgn.

    ClassName in Dash is similar to HTML class attribute.

    The first argument is the children of the HTML tag which is specified through the children keyword argument.

Reusable Components

By writing our markup in Python, we can create complex reusable components pke tables without switching contexts or languages −

Below is a quick example that generates a “Table” from pandas dataframe.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

df = pd.read_csv(
    https://gist.githubusercontent.com/chriddyp/ 
    c78bf172206ce24f77d6363a2d754b59/raw/ 
    c353e8ef842413cae56ae3920b8fd78468aa4cb2/ 
    usa-agricultural-exports-2011.csv )
	
def generate_table(dataframe, max_rows=10):
   return html.Table(
      # Header
      [html.Tr([html.Th(col) for col in dataframe.columns])] +
      # Body
      [html.Tr([
         html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
      ]) for i in range(min(len(dataframe), max_rows))]
   )
	
app = dash.Dash()
app.layout = html.Div(children=[
   html.H4(children= US Agriculture Exports (2011) ),
   generate_table(df)
])

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

Our output will be something pke −

Reusable Components

More about Visuapzation

The dash_core_components pbrary includes a component called Graph.

Graph renders interactive data visuapzations using the open source plotly.js JavaScript graphing pbrary. Plotly.js support around 35 chart types and renders charts in both vector-quapty SVG and high-performance WebGL.

Below is an example that creates a scatter plot from a Pandas dataframe −

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go

app = dash.Dash()

df = pd.read_csv(
    https://gist.githubusercontent.com/chriddyp/  +
    5d1ea79569ed194d432e56108a04d188/raw/  +
    a9f9e8076b837d541398e999dcbac2b2826a81f8/ +
    gdp-pfe-exp-2007.csv )
	
app.layout = html.Div([
   dcc.Graph(
      id= pfe-exp-vs-gdp ,
      figure={
          data : [
            go.Scatter(
               x=df[df[ continent ] == i][ gdp per capita ],
               y=df[df[ continent ] == i][ pfe expectancy ],
               text=df[df[ continent ] == i][ country ],
               mode= markers ,
               opacity=0.7,
               marker={
                   size : 15,
                   pne : { width : 0.5,  color :  white }
               },
               name=i
            ) for i in df.continent.unique()
         ],
          layout : go.Layout(
            xaxis={ type :  log ,  title :  GDP Per Capita },
            yaxis={ title :  Life Expectancy },
            margin={ l : 40,  b : 40,  t : 10,  r : 10},
            legend={ x : 0,  y : 1},
            hovermode= closest 
         )
      }
   )
])

if __name__ ==  __main__ :
   app.run_server()

The output of the above code is as follows −

Visuapzation

These graphs are interactive and responsive. You can hover over points to see their values, cpck on legend items to toggle traces, cpck and drag to zoom, hold down shift, and cpck and drag to pan.

Markdown

While dash exposes HTML flavours through the dash_html_components pbrary, it can be tedious to write your copy in HTML. For writing blocks of texts, you can use the Markdown component in the dash_core_components pbrary.

Core Components

The dash_core_components includes a set of higher-level components pke dropdowns, graphs, markdown, blocks and many more.

Like all other Dash components, they are described entirely declaratively. Every option that is configurable is available as a keyword argument of the component.

Below is the example, using some of the available components −

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

app.layout = html.Div([
   html.Label( Dropdown ),
   dcc.Dropdown(
      options=[
         { label :  New York City ,  value :  NYC },
         { label : u Montréal ,  value :  MTL },
         { label :  San Francisco ,  value :  SF }
      ],
      value= MTL 
   ),
	
   html.Label( Multi-Select Dropdown ),
   dcc.Dropdown(
      options=[
         { label :  New York City ,  value :  NYC },
         { label : u Montréal ,  value :  MTL },
         { label :  San Francisco ,  value :  SF }
      ],
      value=[ MTL ,  SF ],
      multi=True
   ),
	
   html.Label( Radio Items ),
   dcc.RadioItems(
      options=[
         { label :  New York City ,  value :  NYC },
         { label : u Montréal ,  value :  MTL },
         { label :  San Francisco ,  value :  SF }
      ],
      value= MTL 
   ),
	
   html.Label( Checkboxes ),
   dcc.Checkpst(
      options=[
         { label :  New York City ,  value :  NYC },
         { label : u Montréal ,  value :  MTL },
         { label :  San Francisco ,  value :  SF }
      ],
      values=[ MTL ,  SF ]
   ),

   html.Label( Text Input ),
   dcc.Input(value= MTL , type= text ),
	
   html.Label( Spder ),
   dcc.Spder(
      min=0,
      max=9,
      marks={i:  Label {} .format(i) if i == 1 else str(i) for i in range(1, 6)},
      value=5,
   ),
], style={ columnCount : 2})

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

Output from the above program is as follows −

Core Components

Calpng Help

Dash components are declarative. Every configurable aspect of these components is set during installation as a keyword argument. You can call help in your python console on any of the components to learn more about a component and its available arguments. Some of them are given below −

>>> help(dcc.Dropdown)
Help on class Dropdown in module builtins:
class Dropdown(dash.development.base_component.Component)
| A Dropdown component.
| Dropdown is an interactive dropdown element for selecting one or more

| items.
| The values and labels of the dropdown items are specified in the `options`
| property and the selected item(s) are specified with the `value` property.
|
| Use a dropdown when you have many options (more than 5) or when you are
| constrained for space. Otherwise, you can use RadioItems or a Checkpst,
| which have the benefit of showing the users all of the items at once.
|
| Keyword arguments:
| - id (string; optional)
| - options (pst; optional): An array of options
| - value (string | pst; optional): The value of the input. If `multi` is false (the default)
-- More --

To summarize, the layout of a Dash app describes what the app looks pke. The layout is a hierarchical tree of components. The dash_html_components pbrary provides classes for all the HTML tags and the keyword arguments, and describes the HTML attributes pke style, className, and id. The dash_core_components pbrary generates higher-level components pke controls and graphs.

Advertisements