You need to enable JavaScript to run this app. Dash中点击DataTable选中值生成对应bar plot的实现方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

Dash中点击DataTable选中值生成对应bar plot的实现方法咨询

Dash单列表格点击生成柱状图实现方案

这个需求可以通过Dash Table的行选中回调结合Plotly图表组件实现,以下是完整可运行的实现代码和说明:

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

# 初始化应用
app = dash.Dash(__name__)

# 构造表格数据
df = pd.DataFrame({'Values': [1, 2, 3, 4]})

# 页面布局配置
app.layout = html.Div([
    html.H4("数值选择演示"),
    dash_table.DataTable(
        id='value-table',
        data=df.to_dict('records'),
        columns=[{'name': col, 'id': col} for col in df.columns],
        row_selectable='single',  # 开启单行选中模式
        selected_rows=[0],  # 默认选中第一行,进入页面就有默认图表
        style_table={'width': '300px', 'margin': '20px 0'}
    ),
    dcc.Graph(id='bar-plot')
])

# 回调逻辑:选中表格行更新柱状图
@app.callback(
    Output('bar-plot', 'figure'),
    Input('value-table', 'selected_rows')
)
def update_bar_chart(selected_rows):
    # 无选中行时返回提示图
    if not selected_rows:
        return px.bar(title="请点击表格选中任意数值")
    # 提取选中的数值
    target_value = df.iloc[selected_rows[0]]['Values']
    # 生成对应柱状图
    fig = px.bar(
        x=['选中数值'],
        y=[target_value],
        text=[target_value],
        title=f"当前选中值:{target_value}"
    )
    # 优化图表展示
    fig.update_traces(textposition='outside')
    fig.update_layout(yaxis_range=[0, df['Values'].max() + 1])
    return fig

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

实现说明

  • 依赖安装:运行代码前先执行pip install dash pandas plotly安装所需依赖
  • 表格核心配置:给dash_table.DataTable设置row_selectable="single"开启单行选中功能,选中行的索引会自动同步到selected_rows属性
  • 回调逻辑:绑定表格的selected_rows作为回调输入,每次点击切换选中行时会自动触发回调,更新柱状图数据
  • 运行效果:启动脚本后访问本地服务地址,点击表格任意行即可看到柱状图同步更新为对应数值的展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 21:27:02