You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅使用Plotly实现带下拉菜单筛选功能的交互式数据表格

完整实现代码
import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({"Date":["2020-01-27","2020-02-27","2020-03-27"],
                   "A_item":[2, 8, 0],
                   "B_item":[1, 7, 10],
                   "C_item":[9, 2, 9],
                   "Channel_type":["Channel_1", "Channel_1", "Channel_2"]
                   })

# 定义表格需要展示的列
show_cols = ["Date", "A_item", "B_item", "C_item"]
# 初始化默认展示Channel_1的数据
default_df = df[df['Channel_type'] == 'Channel_1'][show_cols]

fig = go.Figure()
fig.add_trace(go.Table(
    header=dict(
        values=show_cols,
        font=dict(size=12),
        align="left"
    ),
    cells=dict(
        values=[default_df[col] for col in show_cols],
        align = "left")
    ))

buttons=[]
for channel in df['Channel_type'].unique():
    # 每次筛选对应渠道的数据,更新表格单元格内容
    filter_df = df[df['Channel_type'] == channel][show_cols]
    buttons.append(dict(method='update',
                        label=channel,
                        args=[{"cells": {"values": [filter_df[col] for col in show_cols]}}])
                  )

updatemenu = []
your_menu = dict(
    buttons=buttons,
    direction='down',
    showactive=True,
    # 调整下拉菜单位置,避免挡住表格
    x=0.1,
    y=1.15,
    xanchor='left',
    yanchor='top'
)
updatemenu.append(your_menu)

fig.update_layout(
    updatemenus=updatemenu,
    # 可选调整标题
    title_text="渠道数据动态查询表"
)

# 直接导出为单个HTML文件,可直接分享给其他用户打开使用
# fig.write_html("dynamic_channel_table.html")
fig.show()
核心修改说明
  • 提前定义要展示的列名,解决原代码中items变量未定义的报错问题
  • 初始化表格时默认加载第一个渠道的数据,保证文件打开即可看到正常内容
  • 下拉按钮的update参数直接绑定对应渠道的筛选数据,切换时自动更新表格的单元格内容
  • 导出的单个HTML文件无任何依赖,其他用户打开即可使用下拉切换功能,完全满足分享需求

内容的提问来源于stack exchange,提问作者j_90

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:39:02