<p>Python如何制作数据看板?答案很明确,Dash框架是目前一个非常成熟且功能强大的选择。它让开发者能够纯粹使用Python代码来构建高度交互式的Web应用和数据看板,省去了学习复杂前端技术(如JavaScript、HTML或CSS)的麻烦。对于那些专注于数据分析和建模,但又希望将成果直观地展现给非技术用户的Python开发者来说,Dash无疑是一座沟通的桥梁,让你的数据真正“动”起来,变得可探索、可交互。
dash.Dash
app.layout
dash.html.Div
dash.html.H1
dash.dcc.Graph
dash.dcc.Dropdown
@app.callback
import dash
from dash import html, dcc
import plotly.express as px
import pandas as pd
# 1. 初始化Dash应用
app = dash.Dash(__name__)
# 准备一些简单的数据
df = pd.DataFrame({
"水果": ["苹果", "橙子", "香蕉", "苹果", "橙子", "香蕉"],
"数量": [4, 1, 2, 2, 4, 5],
"城市": ["北京", "北京", "北京", "上海", "上海", "上海"]
})
# 创建一个简单的柱状图
fig = px.bar(df, x="水果", y="数量", color="城市", barmode="group")
# 2. 定义应用布局
app.layout = html.Div(children=[
html.H1(children='我的第一个Dash数据看板'),
html.Div(children='''
一个简单的水果销售数据展示。
'''),
dcc.Graph(
id='example-graph',
figure=fig
)
])
# 3. 运行应用
if __name__ == '__main__':
app.run_server(debug=True)dash.Dash(__name__)
app.layout
dash.html
dash.dcc
dash.html
html.Div
<div>
html.H1
<h1>
html.P
<p>
html.Div
dash.dcc
dcc.Graph
dcc.Dropdown
dcc.Slider
dcc.Input
dcc.Tabs
dcc.Store
@app.callback
dash.dependencies
Output
Input
State
# ... (前面的导入和df定义不变) ...
app.layout = html.Div([
html.H1("城市水果销售看板"),
dcc.Dropdown(
id='city-selector',
options=[{'label': i, 'value': i} for i in df['城市'].unique()],
value='北京', # 默认选中北京
clearable=False
),
dcc.Graph(id='live-update-graph')
])
@app.callback(
dash.Output('live-update-graph', 'figure'),
dash.Input('city-selector', 'value')
)
def update_graph(selected_city):
filtered_df = df[df['城市'] == selected_city]
fig = px.bar(filtered_df, x="水果", y="数量", title=f"{selected_city}水果销售情况")
return fig
# ... (运行app的代码不变) ...dcc.Dropdown
value
update_graph
update_graph
dcc.Graph
figure
@app.callback
Output
Input
State
2
@app.callback
Output
Output
Output('my-graph', 'figure')my-graph
dcc.Graph
figure
Input
Input
Input
Input('dropdown-menu', 'value')Input
State
Input
State
Input
Input
State
# ... (导入和df定义不变) ...
app.layout = html.Div([
html.H1("动态水果销售分析"),
html.Div([
html.Label("选择城市:"),
dcc.Dropdown(
id='city-dropdown',
options=[{'label': i, 'value': i} for i in df['城市'].unique()],
value='北京',
clearable=False,
style={'width': '50%', 'display': 'inline-block'}
),
html.Label("选择数量范围:", style={'marginLeft': '20px'}),
dcc.RangeSlider(
id='quantity-slider',
min=df['数量'].min(),
max=df['数量'].max(),
step=1,
value=[df['数量'].min(), df['数量'].max()],
marks={str(i): str(i) for i in range(df['数量'].min(), df['数量'].max() + 1)},
tooltip={"placement": "bottom", "always_visible": True},
style={'width': '40%', 'display': 'inline-block', 'marginLeft': '10px'}
)
]),
dcc.Graph(id='filtered-sales-graph')
])
@app.callback(
dash.Output('filtered-sales-graph', 'figure'),
[dash.Input('city-dropdown', 'value'),
dash.Input('quantity-slider', 'value')]
)
def update_filtered_graph(selected_city, quantity_range):
low_qty, high_qty = quantity_range
filtered_df = df[
(df['城市'] == selected_city) &
(df['数量'] >= low_qty) &
(df['数量'] <= high_qty)
]
fig = px.bar(filtered_df, x="水果", y="数量",
title=f"{selected_city} - 数量在 {low_qty}-{high_qty} 的水果销售")
return fig
# ... (运行app的代码不变) ...update_filtered_graph
Input
city-dropdown
value
quantity-slider
value
dcc.Store
prevent_initial_call=True
html.Div
html.Div
app.layout = html.Div([
html.Div([ # 左侧区域
html.H2("控制面板"),
dcc.Dropdown(...),
dcc.RangeSlider(...)
], style={'width': '30%', 'float': 'left', 'padding': '20px'}),
html.Div([ # 右侧图表区域
html.H2("数据可视化"),
dcc.Graph(...)
], style={'width': '65%', 'float': 'right', 'padding': '20px'})
])style
assets
# assets/styles.css
body {
font-family: Arial, sans-serif;
margin: 0;
background-color: #f4f4f4;
}
.container {
max-width: 1200px;
margin: 20px auto;
background-color: white;
padding: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.row {
display: flex;
flex-wrap: wrap;
}
.col-6 {
flex: 0 0 50%;
padding: 10px;
box-sizing: border-box;
}className
app.layout = html.Div(className='container', children=[
html.Div(className='row', children=[
html.Div(className='col-6', children=[
html.H2("控制面板"),
dcc.Dropdown(...)
]),
html.Div(className='col-6', children=[
html.H2("数据可视化"),
dcc.Graph(...)
])
])
])import dash_bootstrap_components as dbc
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.H1("我的Dash看板"), width=12, className="text-center my-4")
]),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader("数据筛选"),
dbc.CardBody([
html.P("选择城市:"),
dcc.Dropdown(
id='city-dropdown-dbc',
options=[{'label': i, 'value': i} for i in df['城市'].unique()],
value='北京',
clearable=False
)
])
])
], width=4),
dbc.Col([
dbc.Card([
dbc.CardHeader("图表展示"),
dbc.CardBody([
dcc.Graph(id='filtered-sales-graph-dbc')
])
])
], width=8)
])
], fluid=True) # fluid=True让容器宽度充满整个屏幕dbc.themes.BOOTSTRAP
dbc.Container
dbc.Row
dbc.Col
dbc.Card
dcc.Loading
try-except
html.Div
html.Small
dbc.Tooltip
以上就是Python如何制作数据看板?Dash框架入门的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号