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

如何在Altair中使用selection_point实现selection_multi的功能?

用selection_point替代selection_multi实现多选功能的正确方法

Altair中selection_multi被弃用后,替换为selection_point时需要注意两者的默认行为差异——selection_multi默认支持多选切换,而selection_point默认是单选,必须显式配置参数才能实现相同的多选效果,具体操作如下:

核心参数配置

要让selection_point实现selection_multi的多选能力,必须添加关键参数:

  • toggle=True:允许点击元素切换选中/取消选中状态,模拟原selection_multi的点击多选逻辑
  • 若需要支持框选批量选中,额外添加select='interval'参数

代码示例对比

原selection_multi实现(点击多选)

import altair as alt
from vega_datasets import data

source = data.cars()

# 原多选选择器
selection = alt.selection_multi(fields=['Origin'])
color = alt.condition(selection,
                      alt.Color('Origin:N').legend(None),
                      alt.value('lightgray'))

chart = alt.Chart(source).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color=color,
    tooltip=['Name:N', 'Origin:N']
).add_params(selection)

替换为selection_point后的代码

import altair as alt
from vega_datasets import data

source = data.cars()

# 替换后的多选选择器,添加toggle=True实现点击多选
selection = alt.selection_point(fields=['Origin'], toggle=True)
color = alt.condition(selection,
                      alt.Color('Origin:N').legend(None),
                      alt.value('lightgray'))

chart = alt.Chart(source).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color=color,
    tooltip=['Name:N', 'Origin:N']
).add_params(selection)

绑定多选控件的场景

如果原代码使用bind绑定了多选下拉框等组件,替换时只需保留bind参数并确保控件开启multiple=True,同时添加toggle=True:

原selection_multi绑定下拉框

selection = alt.selection_multi(
    fields=['Origin'],
    bind=alt.binding_select(options=['USA', 'Europe', 'Japan'], multiple=True)
)

替换为selection_point后的代码

selection = alt.selection_point(
    fields=['Origin'],
    toggle=True,
    bind=alt.binding_select(options=['USA', 'Europe', 'Japan'], multiple=True)
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:52:10