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

如何让Altair图表的Tooltip始终显示?

实现Altair图表Tooltip始终显示的方法

要让Tooltip无需鼠标悬停就始终显示,你可以通过创建默认选中所有数据点的选择器,并将Tooltip的显示条件绑定到该选择器来实现。以下是修改后的代码:

import altair as alt
from vega_datasets import data

source = data.cars()

# 创建默认选中所有数据点的选择器,绑定设为None避免交互修改选择状态
all_points = alt.selection_point(
    fields=['Name'],  # 用唯一标识字段确保选中所有点
    bind=None,
    init=source[['Name']].to_dict('records')  # 初始化选中全部数据点
)

alt.Chart(source).mark_circle(size=60).encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin',
    tooltip=alt.Tooltip(['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon'])
).add_params(all_points).interactive()

原理说明

  • selection_point 创建选择器后,通过init参数默认选中所有数据点,bind=None禁止用户通过交互修改选择状态
  • 绑定Tooltip后,选择器默认激活的状态会让所有数据点的Tooltip始终显示,无需鼠标悬停

如果需要调整Tooltip的样式,贴近原生悬停效果,可以添加configure_tooltip配置:

alt.Chart(source).mark_circle(size=60).encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin',
    tooltip=alt.Tooltip(['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon'])
).add_params(all_points).configure_tooltip(
    backgroundColor='white',
    borderColor='gray',
    cornerRadius=5,
    padding=10
).interactive()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:30:50