Dash 快速上手指南:用 Python 做炫酷图表网站

发布于:2025-06-24 ⋅ 阅读:(17) ⋅ 点赞:(0)

前言

Dash 是由 Plotly 团队开发的 Python Web 框架,专为数据可视化而生。如果你熟悉 Python 和 Pandas,却对 HTML/JS/CSS 一无所知,那么 Dash 会成为你构建数据应用的利器!

Dash 简介

Dash 是一个纯 Python 构建的 Web 应用框架,适用于构建交互式仪表盘、数据可视化平台、数据监控界面等。

  • 核心基于 Flask + Plotly + React

  • 组件丰富,适合数据展示与交互

  • 全部用 Python 编写,不需前端经验

环境安装与启动方式

安装命令

pip install dash pandas plotly

启动示例

from dash import Dash, html

app = Dash(__name__)
app.layout = html.Div(children=[
    html.H1("Dash Dash Dash"),html.H2("Dash Dash Dash"),html.H3("Dash Dash Dash"),
    html.P("这是一个最小的 Dash 应用。")
])

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

在这里插入图片描述

用 Dash 绘制动态图表

绘制简单折线图

import pandas as pd
import plotly.express as px
from dash import Dash, html, dcc

# 准备数据
df = pd.DataFrame({
    "日期": pd.date_range("2023-01-01", periods=7),
    "销售额": [100, 150, 200, 180, 220, 250, 300]
})

# 创建图表
fig = px.line(df, x="日期", y="销售额", title="一周销售额变化")

# 构建 Dash 应用
app = Dash(__name__)
app.layout = html.Div([
    html.H2("销售数据仪表板"),
    dcc.Graph(figure=fig)
])

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

在这里插入图片描述

加入交互

下拉选择

import pandas as pd
import plotly.express as px
from dash import Dash, dcc, html, Input, Output

# 示例数据
data = {
    "城市": ["北京", "上海", "广州"] * 7,
    "日期": pd.date_range("2023-01-01", periods=7).tolist() * 3,
    "销售额": [100,120,150,130,170,180,200, 90,110,140,160,150,180,210, 80,90,100,120,140,160,180]
}
df = pd.DataFrame(data)

app = Dash(__name__)
# 使用 `dcc.Dropdown` 实现选择器
app.layout = html.Div([
    html.H3("城市销售额变化"),
    dcc.Dropdown(options=[
        {"label": city, "value": city} for city in df["城市"].unique()
    ], value="北京", id="city-select"),
    dcc.Graph(id="sales-graph")
])

动态更新


# 使用回调函数实现动态图表更新
@app.callback(
    Output("sales-graph", "figure"),
    Input("city-select", "value")
)
def update_graph(selected_city):
    filtered = df[df["城市"] == selected_city]
    fig = px.line(filtered, x="日期", y="销售额", title=f"{selected_city} 的销售额")
    return fig

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

在这里插入图片描述

部署方式

部署方式 说明
本地运行 python app.py 启动,默认8050端口
Render / Heroku 可上传 Flask/Dash 项目部署
Dash Enterprise Plotly 官方的商业部署平台

总结

一句话总结: Dash 是数据工程师和分析师打造可视化仪表盘的高效利器,兼顾美观和功能性!

参考

Python 前端框架/工具合集
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到