Article directory
1 Introduction
https://dash.plotly.com/
https://dash.gallery/Portal/
Dash is a Python library for building web applications without JavaScript.
Dash is the most downloaded and trusted Python framework for building ML and data science web applications.
Dash is a python library used to create web applications. It is built on Plotly.js (developed by the same team), React and Flask. The main user group is data analysts and AI practitioners, which can help them quickly build very A beautiful web application that doesn’t require you to know JavaScript.
Built on Plotly.js, React, and Flask, Dash combines modern UI elements like dropdowns, sliders, and graphs with your analytical Python code.
Dash can be installed using pip. It can be used to start an http server, python calls it to draw graphs, and it internally replaces these graphs with JavaScript for data analysis and display.
2. Installation
pip install pandas
pip install dash
# pip install dash --user -i https://pypi.tuna.tsinghua.edu.cn/simple
- Minimal Dash Application
A minimal Dash application usually looks like this:
from dash import Dash, html, dcc, callback, Output, Input
import plotly.express as px
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = Dash(__name__)
app.layout = html.Div([
html.H1(children='Title of Dash App', style={
'textAlign':'center'}),
dcc.Dropdown(df.country.unique(), 'Canada', id='dropdown-selection'),
dcc.Graph(id='graph-content')
])
@callback(
Output('graph-content', 'figure'),
Input('dropdown-selection', 'value')
)
def update_graph(value):
dff = df[df.country==value]
return px.line(dff, x='year', y='pop')
if __name__ == '__main__':
app.run(debug=True)
3. Function examples
3.1 Hello World
The code below creates a very small "Hello World" Dash application.
from dash import Dash, html
app = Dash(__name__)
app.layout = html.Div([
html.Div(children='Hello World, 爱看书的小沐!')
])
if __name__ == '__main__':
app.run(debug=True)
3.2 Connect to data
There are many ways to add data to your application: API, external database, local files, JSON files, etc. In this example, we'll focus on one of the most common ways to merge data from CSV sheets.
from dash import Dash, html, dash_table
import pandas as pd
# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
# Initialize the app
app = Dash(__name__)
# App layout
app.layout = html.Div([
html.Div(children='My First App with Data'),
dash_table.DataTable(data=df.to_dict('records'), page_size=10)
])
# Run the app
if __name__ == '__main__':
app.run(debug=True)
3.3 Visualizing data
The Plotly graphics library has over 50 chart types to choose from. In this example we will use a histogram.
from dash import Dash, html, dash_table, dcc
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(__name__)
# App layout
app.layout = html.Div([
html.Div(children='My First App with Data and a Graph'),
dash_table.DataTable(data=df.to_dict('records'), page_size=10),
dcc.Graph(figure=px.histogram(df, x='continent', y='lifeExp', histfunc='avg'))
])
# Run the app
if __name__ == '__main__':
app.run(debug=True)
3.4 Controls and callbacks
So far, you have built a static application that displays tabular data and graphics. However, as you develop more complex Dash applications, you may want to give your application users more freedom to interact with the application and explore the data more deeply. To do this, you need to add controls to your app using callback functions.
In this example, we will add radio buttons to the app layout. We will then build callbacks to create the interaction between the radio buttons and the histogram.
from dash import Dash, html, dash_table, dcc, callback, Output, Input
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(__name__)
# App layout
app.layout = html.Div([
html.Div(children='My First App with Data, Graph, and Controls'),
html.Hr(),
dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'], value='lifeExp', id='controls-and-radio-item'),
dash_table.DataTable(data=df.to_dict('records'), page_size=6),
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(df, x='continent', y=col_chosen, histfunc='avg')
return fig
# Run the app
if __name__ == '__main__':
app.run(debug=True)
3.5 Set the application style
The example in the previous section uses Dash HTML components to build a simple app layout, but you can style your app to make it look more professional.
- This section will provide a brief overview of the various tools you can use to enhance your Dash application layout styling:
- HTML and CSS
- Dash Design Kit (DDK)
- Dash Bootstrap Components
- Dash Mantine Components
3.5.1 HTML and CSS
HTML and CSS are the lowest-level interfaces for rendering content on the web. HTML is a set of components and CSS is a set of styles applied to those components. CSS styles can be applied within components via properties, or they can be defined as separate CSS files that reference properties.
from dash import Dash, html, dash_table, dcc, callback, Output, Input
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_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(__name__, external_stylesheets=external_stylesheets)
# App layout
app.layout = html.Div([
html.Div(className='row', children='My First App with Data, Graph, and Controls',
style={
'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=[
dash_table.DataTable(data=df.to_dict('records'), page_size=11, style_table={
'overflowX': 'auto'})
]),
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(df, x='continent', y=col_chosen, histfunc='avg')
return fig
# Run the app
if __name__ == '__main__':
app.run(debug=True)
3.5.2 Dash Design Kit (DDK)
Dash Design Toolkit is our high-level UI framework built specifically for Dash. With the Dash design toolkit, you don't need to use HTML or CSS. By default, the app is mobile responsive and everything is themed.
Please note that you will not be able to run this example without a Dash enterprise license.
from dash import Dash, html, dash_table, dcc, callback, Output, Input
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(__name__)
# App layout
app.layout = ddk.App([
ddk.Header(ddk.Title('My First App with Data, Graph, and Controls')),
dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'],
value='lifeExp',
inline=True,
id='my-ddk-radio-items-final'),
ddk.Row([
ddk.Card([
dash_table.DataTable(data=df.to_dict('records'), page_size=12, style_table={
'overflowX': 'auto'})
], 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(df, x='continent', y=col_chosen, histfunc='avg')
return fig
# Run the app
if __name__ == '__main__':
app.run(debug=True)
3.5.3 Dash Bootstrap Components
Dash Bootstrap is a community-maintained library built on the bootstrap component system. Although it is not officially maintained or supported by Plotly, Dash Bootstrap is a powerful way to build elegant application layouts. Note that we first define a row and then use the and component to define the width of the columns within the row.
pip install dash-bootstrap-components
# Import packages
from dash import Dash, html, dash_table, dcc, callback, Output, Input
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_stylesheets = [dbc.themes.CERULEAN]
app = Dash(__name__, external_stylesheets=external_stylesheets)
# App layout
app.layout = dbc.Container([
dbc.Row([
html.Div('My First App with Data, Graph, and 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([
dash_table.DataTable(data=df.to_dict('records'), page_size=12, style_table={
'overflowX': 'auto'})
], 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(df, x='continent', y=col_chosen, histfunc='avg')
return fig
# Run the app
if __name__ == '__main__':
app.run(debug=True)
3.5.4 Dash Mantine Components
Dash Mantine is a community-maintained library built on the Mantine component system. While it's not officially maintained or supported by the Plotly team, Dash Mantine is another powerful way to customize your app's layout. The dash component uses grid modules to build layouts.
pip install dash-mantine-components
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px
import dash_mantine_components as dmc
# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
# Initialize the app - incorporate a Dash Mantine theme
external_stylesheets = [dmc.theme.DEFAULT_COLORS]
app = Dash(__name__, external_stylesheets=external_stylesheets)
# App layout
app.layout = dmc.Container([
dmc.Title('My First App with Data, Graph, and Controls', color="blue", size="h3"),
dmc.RadioGroup(
[dmc.Radio(i, value=i) for i in ['pop', 'lifeExp', 'gdpPercap']],
id='my-dmc-radio-item',
value='lifeExp',
size="sm"
),
dmc.Grid([
dmc.Col([
dash_table.DataTable(data=df.to_dict('records'), page_size=12, style_table={
'overflowX': 'auto'})
], span=6),
dmc.Col([
dcc.Graph(figure={
}, id='graph-placeholder')
], span=6),
]),
], fluid=True)
# Add controls to build the interaction
@callback(
Output(component_id='graph-placeholder', component_property='figure'),
Input(component_id='my-dmc-radio-item', component_property='value')
)
def update_graph(col_chosen):
fig = px.histogram(df, x='continent', y=col_chosen, histfunc='avg')
return fig
# Run the App
if __name__ == '__main__':
app.run(debug=True)
4. More examples
4.1 Basic Dashboard
import dash
import dash_core_components as dcc
import dash_html_components as html
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'
}
}
)
])
if __name__ == '__main__':
app.run_server()
4.2 Using Callbacks
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
app = dash.Dash()
app.layout = html.Div(children =[
dcc.Input(id ='input',
value ='Enter a number',
type ='text'),
html.Div(id ='output')
])
@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"
if __name__ == '__main__':
app.run_server()
4.3 Use Dash to generate HTML
# -*- 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='你好,Dash'),
html.Div(children='''
Dash: Python测试示例'''),
dcc.Graph(
id='example-graph',
figure={
'data': [
{
'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': '北京'},
{
'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': '天津'},
],
'layout': {
'title': 'Dash数据可视化'
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
4.4 Reusable components
# -*- coding: utf-8 -*-
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_talbe(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.css.append_css(
{
"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})
app.layout = html.Div(children=[
html.H4(children='2011年美国农业出口数据表'),
generate_talbe(df)
])
if __name__ == '__main__':
app.run_server(debug=True)
4.5 Visualization Example
# -*- coding: utf-8 -*-
import dash
import pandas as pd
import plotly.graph_objs as go
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/' +
'5d1ea79569ed194d432e56108a04d188/raw/' +
'a9f9e8076b837d541398e999dcbac2b2826a81f8/' +
'gdp-life-exp-2007.csv')
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure={
'data': [
go.Scatter(
x=df[df['continent'] == i]['gdp per capita'],
y=df[df['continent'] == i]['life expectancy'],
text=df[df['continent'] == i]['country'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {
'width': 0.5, 'color': 'white'}
},
name=i
) for i in df.continent.unique()
],
'layout': go.Layout(
xaxis={
'type': 'log', 'title': '人均GDP'},
yaxis={
'title': '平均寿命'},
margin={
'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={
'x': 0, 'y': 1},
hovermode='closest'
)
}
)
])
if __name__ == '__main__':
app.run_server()
4.6 Dash and Markdown
# -*- coding: utf-8 -*-
import dash_core_components as dcc
import dash_html_components as html
import dash
app = dash.Dash()
Markdown_text = '''
#### 标题
# 1级标题 \#
## 2级标题 \##
#### 分割线
***
### 粗体斜体
*斜体*,文字两边各写一个\*星号
**粗体**,文字两边各写两个\*星号
1. [有提示的链接](http://url.com/ "有提示的链接")
2. [没有提示的链接](http://url.com/)
#### 表格 不支持
姓名|语文|数学|总成绩
---|:---|:---:|---:
张三|100|90|190
#### 引用文字
使用\>是一级引用,使用两个>,即>>,是引用里面的引用
>引用文字
>>引用里面的引用
'''
app.css.append_css(
{
"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})
app.layout = html.Div([
dcc.Markdown(children=Markdown_text)
])
if __name__ == '__main__':
app.run_server()
4.7 Core components
from dash import dcc, html, Dash
from dash.dependencies import Input, Output
app = Dash(__name__)
# 定义下拉选项
dropdown_options = [{
'label': 'Blue', 'value': 'blue'},
{
'label': 'Red', 'value': 'red'},
{
'label': 'Yellow', 'value': 'yellow'},
{
'label': 'Green', 'value': 'green'}]
# 定义app布局
app.layout = html.Div([
dcc.Dropdown(options=dropdown_options,
value='blue',
id='color-dropdown'),
html.Div('Hello, world!', id='output-div', style={
'padding': '20px'})
], style={
'backgroundColor': 'blue'}) # Set the initial background color
# Define the app callback
@app.callback(Output('output-div', 'style'), [Input('color-dropdown', 'value')])
def update_output_background_color(selected_color):
if selected_color:
# 更新div的背景色
return {
'backgroundColor': selected_color}
if __name__ == '__main__':
app.run_server(debug=True)
Conclusion
如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;
╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地
//(ㄒoㄒ)//,就在评论处留言,作者继续改进;
o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;
(✿◡‿◡)
感谢各位大佬童鞋们的支持!
( ´ ▽´ )ノ ( ´ ▽´)! ! !