×

注意!页面内容来自http://dash.plotly.com/tutorial,本站不储存任何内容,为了更好的阅读体验进行在线解析,若有广告出现,请及时反馈。若您觉得侵犯了您的利益,请通知我们进行删除,然后访问 原网页

Dash in 20 Minutes

By the end of this tutorialyou will understand the basic building blocks of Dash and you will know how to build this app:

View app

# Import packages
from dash import DashhtmldcccallbackOutputInput
import dash_ag_grid as dag
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = [
    html.Div(children='My First App with DataGraphand Controls'),
    html.Hr(),
    dcc.RadioItems(options=['pop''lifeExp''gdpPercap']value='lifeExp'id='my-final-radio-item-example'),
    dag.AgGrid(
        rowData=df.to_dict('records'),
        columnDefs=[{"field": i} for i in df.columns]
    ),
    dcc.Graph(figure={}id='my-final-graph-example')
]

# Add controls to build the interaction
@callback(
    Output(component_id='my-final-graph-example'component_property='figure'),
    Input(component_id='my-final-radio-item-example'component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(dfx='continent'y=col_chosenhistfunc='avg')
    return fig

# Run the app
if __name__ == '__main__':
    app.run(debug=True)
My First App with DataGraphand Controls

Hello World

Building and launching an app with Dash can be done with just 5 lines of code.

Open a Python IDE on your computercreate an app.py file with the code below and install Dash if you haven’t done so already.
To launch the apptype into your terminal the command python app.py. Thengo to the http link.

Alternativelywith Dash 2.11 or lateryou can run this app and other examples from this documentation in a Jupyter Notebook.

The code below creates a very small “Hello World” Dash app.

from dash import Dashhtml

app = Dash()

# Requires Dash 2.17.0 or later
app.layout = [html.Div(children='Hello World')]

if __name__ == '__main__':
    app.run(debug=True)
Hello World

Follow this example gif (using VS Code) if you are not sure how to set up the app:

launch app

Hello World: Code Breakdown

# Import packages
from dash import Dashhtml
  • When creating Dash appsyou will almost always use the import statement above. As you create more advanced Dash appsyou will import more packages.
# Initialize the app
app = Dash()
  • This line is known as the Dash constructor and is responsible for initializing your app. It is almost always the same for any Dash app you create.
# App layout
app.layout = [html.Div(children='Hello World')]
  • The app layout represents the app components that will be displayed in the web browser and here is provided as a listthough it could also be a Dash component.
    In this examplea single component was added to the list: an html.Div.
    The Div has a few propertiessuch as childrenwhich we use to add text content to the page: “Hello World”.
# Run the app
if __name__ == '__main__':
    app.run(debug=True)
  • These lines are for running your appand they are almost always the same for any Dash app you create.

Connecting to Data

There are many ways to add data to an app: APIsexternal databaseslocal .txt filesJSON filesand more.
In this examplewe will highlight one of the most common ways of incorporating data from a CSV sheet.

Replace the app.py code from the previous section with the code below. Theninstall pandas and dash-ag-grid (pip install pandas dash-ag-grid) and launch the app.

# Import packages
from dash import Dashhtml
import dash_ag_grid as dag
import pandas as pd

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = [
    html.Div(children='My First App with Data'),
    dag.AgGrid(
        rowData=df.to_dict('records'),
        columnDefs=[{"field": i} for i in df.columns]
    )
]

# Run the app
if __name__ == '__main__':
    app.run(debug=True)
My First App with Data

Connect to Data: Code Breakdown

# Import packages
from dash import Dashhtml
import dash_ag_grid as dag
import pandas as pd
  • We import the dash_ag_grid package (as dag) to display the data inside a Dash AG Grid table. We also import the pandas library to read the CSV sheet data.
# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
  • Here we read the CSV sheet into a pandas dataframe. This will make it easier to slicefilterand inspect the data.

  • If you prefer to use a CSV sheet that is on your computer (and not online)make sure to save it in the same folder that contains the app.py file.
    Thenupdate the line of code to: df = pd.read_csv('NameOfYourFile.csv')

  • If you’re using an Excel sheetmake sure to pip install openpyxl. Thenupdate the line of code to:
    df = pd.read_excel('NameOfYourFile.xlsx'sheet_name='Sheet1')

Tip: You can read the pandas docs on reading data if your data is in a different formator consider using another Python library if you are connecting to a specific database type or file format.
For exampleif you’re considering using Databricks as a backend for your Dash appyou may review their Python documentation for recommendations on how to connect.

# App layout
app.layout = [
    html.Div(children='My First App with Data'),
    dag.AgGrid(
        rowData=df.to_dict('records'),
        columnDefs=[{"field": i} for i in df.columns]
    )
]
  • In addition to the app titlewe add the AG Grid component and read the pandas dataframe into the table. We define the columns using columnDefs.

Visualizing Data

The Plotly graphing library has more than 50 chart types to choose from.
In this examplewe will make use of the histogram chart.

Replace the app.py code from the previous section with the code below.

# Import packages
from dash import Dashhtmldcc
import dash_ag_grid as dag
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = [
    html.Div(children='My First App with Data and a Graph'),
    dag.AgGrid(
        rowData=df.to_dict('records'),
        columnDefs=[{"field": i} for i in df.columns]
    ),
    dcc.Graph(figure=px.histogram(dfx='continent'y='lifeExp'histfunc='avg'))
]

# Run the app
if __name__ == '__main__':
    app.run(debug=True)
My First App with Data and a Graph

Visualize Data: Code Breakdown

# Import packages
from dash import Dashhtmldcc
import dash_ag_grid as dag
import pandas as pd
import plotly.express as px
  • We import the dcc module (DCC stands for Dash Core Components). This module includes a Graph component called dcc.Graphwhich is used to render interactive graphs.

  • We import the dash_ag_grid package (as dag) to display the data in a table.

  • We also import the plotly.express library to build the interactive graphs.

# App layout
app.layout = [
    html.Div(children='My First App with Data and a Graph'),
    dag.AgGrid(
        rowData=df.to_dict('records'),
        columnDefs=[{"field": i} for i in df.columns]
    ),
    dcc.Graph(figure=px.histogram(dfx='continent'y='lifeExp'histfunc='avg'))
]
  • We add the AG Grid componentand below itwe add the graph. Using the plotly.express librarywe build the histogram chart and assign it to the figure property of the dcc.Graph. This displays the histogram in our app.

Controls and Callbacks

So far you have built a static app that displays tabular data and a graph.
Howeveras you develop more sophisticated Dash appsyou will likely want to give the app user more freedom to interact with the app and explore the data in greater depth.
To achieve thatyou will need to add controls to the app by using the callback function.

In this example we will add radio buttons to the app layout. Thenwe will build the callback to create the interaction between the radio buttons and the histogram chart.

# Import packages
from dash import DashhtmldcccallbackOutputInput
import dash_ag_grid as dag
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = [
    html.Div(children='My First App with DataGraphand Controls'),
    html.Hr(),
    dcc.RadioItems(options=['pop''lifeExp''gdpPercap']value='lifeExp'id='controls-and-radio-item'),
    dag.AgGrid(
        rowData=df.to_dict('records'),
        columnDefs=[{"field": i} for i in df.columns]
    ),
    dcc.Graph(figure={}id='controls-and-graph')
]

# Add controls to build the interaction
@callback(
    Output(component_id='controls-and-graph'component_property='figure'),
    Input(component_id='controls-and-radio-item'component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(dfx='continent'y=col_chosenhistfunc='avg')
    return fig

# Run the app
if __name__ == '__main__':
    app.run(debug=True)
My First App with DataGraphand Controls

Controls: Code Breakdown

# Import packages
from dash import DashhtmldcccallbackOutputInput
import dash_ag_grid as dag
  • We import dcc like we did in the previous section to use dcc.Graph. In this examplewe need dcc for dcc.Graph as well as the radio buttons componentdcc.RadioItems.

  • We import dash_ag_grid (as dag) to display the data in a table.

  • To work with the callback in a Dash appwe import the callback module and the two arguments commonly used within the callback: Output and Input.

# App layout
app.layout = [
    html.Div(children='My First App with DataGraphand Controls'),
    html.Hr(),
    dcc.RadioItems(options=['pop''lifeExp''gdpPercap']value='lifeExp'id='controls-and-radio-item'),
    dag.AgGrid(
        rowData=df.to_dict('records'),
        columnDefs=[{"field": i} for i in df.columns]
    ),
    dcc.Graph(figure={}id='controls-and-graph')
]
  • Notice that we add the RadioItems component to the layoutdirectly above the AG Grid.
    There are three optionsone for every radio button. The lifeExp option is assigned to the value propertymaking it the currently selected value.

  • Both the RadioItems and the Graph components were given id names: these will be used by the callback to identify the components.

# Add controls to build the interaction
@callback(
    Output(component_id='controls-and-graph'component_property='figure'),
    Input(component_id='controls-and-radio-item'component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(dfx='continent'y=col_chosenhistfunc='avg')
    return fig
  • The inputs and outputs of our app are the properties of a particular component.
    In this exampleour input is the value property of the component that has the ID “controls-and-radio-item”. If you look back at the layoutyou will see that this is currently lifeExp.
    Our output is the figure property of the component with the ID “controls-and-graph”which is currently an empty dictionary (empty graph).

  • The callback function’s argument col_chosen refers to the component property of the input lifeExp.
    We build the histogram chart inside the callback functionassigning the chosen radio item to the y-axis attribute of the histogram.
    This means that every time the user selects a new radio itemthe figure is rebuilt and the y-axis of the figure is updated.

  • Finallywe return the histogram at the end of the function. This assigns the histogram to the figure property of the dcc.Graphthus displaying the figure in the app.

Styling Your App

The examples in the previous section used Dash HTML Components to build a simple app layoutbut you can your app to look more professional.
This section will give a brief overview of the multiple tools that you can use to enhance the layout of a Dash app:
- HTML and CSS
- Dash Design Kit (DDK)
- Dash Bootstrap Components
- Dash Mantine Components

HTML and CSS

HTML and CSS are the lowest level of interface for rendering content on the web.
The HTML is a set of componentsand CSS is a set of s applied to those components.
CSS s can be applied within components via the propertyor they can be defined as a separate CSS file in reference with the className propertyas in the example below.

# Import packages
from dash import DashhtmldcccallbackOutputInput
import dash_ag_grid as dag
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app - incorporate css
external_sheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(external_sheets=external_sheets)

# App layout
app.layout = [
    html.Div(className='row'children='My First App with DataGraphand Controls',
             ={'textAlign': 'center''color': 'blue''fontSize': 30}),

    html.Div(className='row'children=[
        dcc.RadioItems(options=['pop''lifeExp''gdpPercap'],
                       value='lifeExp',
                       inline=True,
                       id='my-radio-buttons-final')
    ]),

    html.Div(className='row'children=[
        html.Div(className='six columns'children=[
            dag.AgGrid(
                rowData=df.to_dict('records'),
                columnDefs=[{"field": i} for i in df.columns]
            )
        ]),
        html.Div(className='six columns'children=[
            dcc.Graph(figure={}id='histo-chart-final')
        ])
    ])
]

# Add controls to build the interaction
@callback(
    Output(component_id='histo-chart-final'component_property='figure'),
    Input(component_id='my-radio-buttons-final'component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(dfx='continent'y=col_chosenhistfunc='avg')
    return fig

# Run the app
if __name__ == '__main__':
    app.run(debug=True)
My First App with DataGraphand Controls

Dash Design Kit (DDK)

Dash Design Kit is our high level UI framework that is purpose-built for Dash.
With Dash Design Kityou don’t need to use HTML or CSS. Apps are mobile responsive by default and everything is themeable.
Dash Design Kit is licensed as part of Dash Enterprise and officially supported by Plotly.

Here’s an example of what you can do with Dash Design Kit (note that you won’t be able to run this example without a Dash Enterprise license).

# Import packages
from dash import DashhtmldcccallbackOutputInput
import dash_ag_grid as dag
import pandas as pd
import plotly.express as px
import dash_design_kit as ddk

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = ddk.App([
    ddk.Header(ddk.Title('My First App with DataGraphand Controls')),
    dcc.RadioItems(options=['pop''lifeExp''gdpPercap'],
                    value='lifeExp',
                    inline=True,
                    id='my-ddk-radio-items-final'),
    ddk.Row([
        ddk.Card([
            dag.AgGrid(
                rowData=df.to_dict('records'),
                columnDefs=[{"field": i} for i in df.columns]
            )
        ]width=50),
        ddk.Card([
            ddk.Graph(figure={}id='graph-placeholder-ddk-final')
        ]width=50),
    ]),

])

# Add controls to build the interaction
@callback(
    Output(component_id='graph-placeholder-ddk-final'component_property='figure'),
    Input(component_id='my-ddk-radio-items-final'component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(dfx='continent'y=col_chosenhistfunc='avg')
    return fig

# Run the app
if __name__ == '__main__':
    app.run(debug=True)

Dash Bootstrap Components

Dash Bootstrap is a community-maintained library built off of the bootstrap component system.
Although it is not officially maintained or supported by PlotlyDash Bootstrap is a powerful way of building elegant app layouts.
Notice that we first define a row and then the width of columns inside the rowusing the dbc.Row and dbc.Col components.

For the app below to run successfullymake sure to install the Dash Bootstrap Components library: pip install dash-bootstrap-components

Read more about the Dash Bootstrap Components in the third-party documentation.

# Import packages
from dash import DashhtmldcccallbackOutputInput
import dash_ag_grid as dag
import pandas as pd
import plotly.express as px
import dash_bootstrap_components as dbc

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app - incorporate a Dash Bootstrap theme
external_sheets = [dbc.themes.CERULEAN]
app = Dash(__name__external_sheets=external_sheets)

# App layout
app.layout = dbc.Container([
    dbc.Row([
        html.Div('My First App with DataGraphand Controls'className="text-primary text-center fs-3")
    ]),

    dbc.Row([
        dbc.RadioItems(options=[{"label": x"value": x} for x in ['pop''lifeExp''gdpPercap']],
                       value='lifeExp',
                       inline=True,
                       id='radio-buttons-final')
    ]),

    dbc.Row([
        dbc.Col([
            dag.AgGrid(
                rowData=df.to_dict('records'),
                columnDefs=[{"field": i} for i in df.columns]
            )
        ]width=6),

        dbc.Col([
            dcc.Graph(figure={}id='my-first-graph-final')
        ]width=6),
    ]),

]fluid=True)

# Add controls to build the interaction
@callback(
    Output(component_id='my-first-graph-final'component_property='figure'),
    Input(component_id='radio-buttons-final'component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(dfx='continent'y=col_chosenhistfunc='avg')
    return fig

# Run the app
if __name__ == '__main__':
    app.run(debug=True)

Dash Mantine Components

Dash Mantine is a community-maintained library built off of the Mantine component system.
Although it is not officially maintained or supported by the Plotly teamDash Mantine is another powerful way of customizing app layouts.

This example uses the SimpleGrid component to create equal-width columns. The cols prop makes the layout responsiveshowing one
column on smaller screens and two columns from the md breakpoint and up.

For the app below to run successfullymake sure to install the Dash Mantine Components library: pip install dash-mantine-components==2.3.0

Read more about the Dash Mantine Components in the third-party documentation.

from dash import DashdcccallbackOutputInput
import pandas as pd
import plotly.express as px
import dash_mantine_components as dmc
import dash_ag_grid as dag

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

app = Dash()

app.layout = dmc.MantineProvider(
    dmc.Container([
        dmc.Title("My First App with DataGraphand Controls"c="blue"order=3),
        dmc.RadioGroup(
           dmc.Group([dmc.Radio(ivalue=i) for i in  ['pop''lifeExp''gdpPercap']]),
            id='my-dmc-radio-item',
            value='lifeExp',
            p="sm"
        ),
        dmc.SimpleGrid([
            dag.AgGrid(
                rowData=df.to_dict("records"),
                columnDefs=[{"field": i} for i in df.columns],
            ),
            dcc.Graph(figure={}id='graph-placeholder')
        ]cols={"base": 1"md": 2})
    ]fluid=True)
)

@callback(
    Output('graph-placeholder''figure'),
    Input('my-dmc-radio-item''value')
)
def update_graph(col_chosen):
    fig = px.histogram(dfx='continent'y=col_chosenhistfunc='avg')
    return fig

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

Dash Mantine app

Next Steps

Congratulations! You have learned to build and your first Dash app.
This is the first step of an exciting Dash learning journey that will give you the skills and tools to build sophisticated Python analytics apps.
There’s lots more you can learn from the Dash Fundamentals and the rest of this documentation.

When you’re readywhy not get feedback directly from your app’s intended audience?
The beauty of your Dash app is that you can share it as a URL with just a few clicks using Plotly Cloud!
Plotly handles the whole infrastructure so all you need to do is to upload your app files and copy the URL.
Get started with Plotly Cloud for free or learn more.