Python | Dashboard制作

运行环境:jupyter notebook (python 3.12.7) + Pyecharts

1.安装pyecharts

python 复制代码
!pip install pyecharts

验证安装是否成功:

python 复制代码
from pyecharts import __version__
print("Pyecharts版本:", __version__)  # 应显示1.x以上版本

2.运行基础版代码,生成深/浅色双模式HTML

python 复制代码
from pyecharts.charts import Line, Bar, Pie, Scatter, Page
from pyecharts import options as opts
import random

# 生成示例数据
categories = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
data1 = [random.randint(20, 100) for _ in range(7)]
data2 = [random.randint(30, 150) for _ in range(7)]
pie_data = [('A', 45), ('B', 30), ('C', 25)]
scatter_data = [(i, random.randint(10, 50)) for i in range(20)]

# 创建 Page 实例
page = Page(layout=Page.SimplePageLayout)

# 折线图(添加固定ID)
line = (
    Line(init_opts=opts.InitOpts(chart_id="chart_line"))
    .add_xaxis(categories)
    .add_yaxis("Series 1", data1, is_smooth=True)
    .add_yaxis("Series 2", data2, is_smooth=True)
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Weekly Trend"),
        toolbox_opts=opts.ToolboxOpts(),
        tooltip_opts=opts.TooltipOpts(trigger="axis")
    )
)

# 柱状图(添加固定ID)
bar = (
    Bar(init_opts=opts.InitOpts(chart_id="chart_bar"))
    .add_xaxis(categories)
    .add_yaxis("Sales", data1, color="#5793f3")
    .add_yaxis("Profit", data2, color="#d14a61")
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Sales vs Profit"),
        datazoom_opts=opts.DataZoomOpts(),
        toolbox_opts=opts.ToolboxOpts()
    )
)

# 饼图(添加固定ID)
pie = (
    Pie(init_opts=opts.InitOpts(chart_id="chart_pie"))
    .add("", pie_data, radius=["30%", "55%"])
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Market Share"),
        legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%")
    )
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
)

# 散点图(添加固定ID)
scatter = (
    Scatter(init_opts=opts.InitOpts(chart_id="chart_scatter"))
    .add_xaxis([x[0] for x in scatter_data])
    .add_yaxis("Value", [y[1] for y in scatter_data])
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Scatter Distribution"),
        toolbox_opts=opts.ToolboxOpts(),
        visualmap_opts=opts.VisualMapOpts(max_=50)
    )
)

# 将图表添加到 Page
page.add(line, bar, pie, scatter)

# 生成初始 HTML
page.render("dashboard.html")

# ------------- 手动添加交互功能 --------------
def insert_theme_switcher():
    """向生成的 HTML 中插入主题切换组件"""
    with open("dashboard.html", "r", encoding="utf-8") as f:
        html = f.read()

    insert_code = f"""
    <!-- 主题切换按钮 -->
    <div style="position: fixed; top: 20px; right: 20px; z-index: 9999; background: white; padding: 10px; border-radius: 5px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
        <button onclick="changeTheme('light')">☀️ 明亮模式</button>
        <button onclick="changeTheme('dark')">🌙 暗黑模式</button>
    </div>
    <script>
    // 存储图表配置
    var chartConfigs = {{
        chart_line: {line.dump_options()},
        chart_bar: {bar.dump_options()},
        chart_pie: {pie.dump_options()},
        chart_scatter: {scatter.dump_options()}
    }};

    // 主题切换函数
    function changeTheme(theme) {{
        ['chart_line', 'chart_bar', 'chart_pie', 'chart_scatter'].forEach(chartId => {{
            let chart = echarts.getInstanceByDom(document.getElementById(chartId));
            if (chart) chart.dispose();
            let newChart = echarts.init(
                document.getElementById(chartId), 
                theme,
                {{ renderer: 'canvas' }}
            );
            newChart.setOption(chartConfigs[chartId]);
        }});
    }}
    </script>
    """

    # 在 </body> 前插入代码
    new_html = html.replace("</body>", insert_code + "\n</body>")
    with open("dashboard.html", "w", encoding="utf-8") as f:
        f.write(new_html)

insert_theme_switcher()
print("仪表盘生成成功!打开 dashboard.html 查看效果")

HTML截图:

相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github