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

Python Plotly点击散点后关联更新对应数据表格实现方案咨询

可行实现方案

你需要使用Plotly官方的交互式应用框架Dash实现组件联动,原生静态渲染的Plotly图表无法支持点击回调逻辑。

前置依赖安装

执行以下命令安装所需依赖:

pip install dash umap-learn plotly pandas scikit-learn

完整可运行代码

from umap import UMAP
import plotly.express as px
import plotly.graph_objects as go
from dash import Dash, dcc, callback, Input, Output
import pandas as pd

# 统一加载并处理数据集,对齐列名与你使用的csv格式一致
df = px.data.iris()
df.columns = ['sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species', 'species_id']

# 计算UMAP降维结果
features = df.loc[:, :'petalwidth']
umap_2d = UMAP(n_components=2, init='random', random_state=0)
proj_2d = umap_2d.fit_transform(features)

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

# 应用布局:上层散点图,下层表格
app.layout = [
    dcc.Graph(id="umap-scatter"),
    dcc.Graph(id="species-table")
]

# 生成UMAP散点图,将species存入customdata供点击事件获取
@callback(
    Output('umap-scatter', 'figure'),
    Input('umap-scatter', 'id') # 初始化触发
)
def generate_scatter(_):
    fig = px.scatter(
        proj_2d, x=0, y=1,
        color=df.species,
        labels={'color': 'species'},
        custom_data=['species']
    )
    return fig

# 点击散点触发表格更新
@callback(
    Output('species-table', 'figure'),
    Input('umap-scatter', 'clickData')
)
def update_table(click_data):
    # 无点击时默认展示全量数据
    filter_species = df['species'].unique()
    if click_data:
        # 从点击数据中获取对应物种
        filter_species = [click_data['points'][0]['customdata'][0]]
    
    # 筛选对应物种的数据
    filtered_df = df[df['species'].isin(filter_species)]
    
    # 生成表格
    table_fig = go.Figure(data=[go.Table(
        header=dict(values=list(filtered_df.columns[:-1]), # 去掉不需要的species_id列
                    fill_color='paleturquoise',
                    align='left'),
        cells=dict(values=[filtered_df.sepallength, filtered_df.sepalwidth, filtered_df.petallength, filtered_df.petalwidth, filtered_df.species],
                   fill_color='lavender',
                   align='left'))
    ])
    return table_fig

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

使用说明

运行代码后,根据终端提示打开本地服务地址(默认是http://127.0.0.1:8050/),点击散点图中任意点,下方表格会自动筛选展示对应该点所属物种的全部样本数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:57:04