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

如何设置Altair选择区间的默认定义域,使初始显示区间小于全量范围

解决方案:设置Altair选择区间的初始范围

你猜的完全正确——要实现初始显示的区间小于全量刻度范围,只需要给alt.selection_interval()添加init参数来指定初始的选择范围即可。

修改后的完整代码

import altair as alt
from vega_datasets import data

weather = data.seattle_weather()
weather.head()

# 添加init参数指定初始的x轴区间
interval = alt.selection_interval(
    encodings=['x'],
    # 这里设置初始显示2013年1月1日到2013年3月31日的数据
    init={'x': ['2013-01-01', '2013-03-31']}
)

base = alt.Chart(weather).mark_rule(size=2).encode(
    x='date:T',
    y='temp_min:Q',
    y2='temp_max:Q',
    color='weather:N'
)

chart = base.encode(
    x=alt.X('date:T', scale=alt.Scale(domain=interval.ref()))
).properties(
    width=800,
    height=300
)

view = base.add_selection(
    interval
).properties(
    width=800,
    height=50,
)

chart & view

关键说明

  • init参数接收一个字典,键对应你在encodings里指定的字段(这里是x),值是一个包含起始值和结束值的列表。
  • 因为你的x轴是时间类型(date:T),所以直接传入符合ISO格式的日期字符串即可被Altair正确解析。
  • 如果需要更动态的初始范围(比如基于数据的前20%区间),可以先从数据中计算出对应的起始和结束值,再传入init,示例如下:
    # 计算数据前20%的日期范围
    start_date = weather['date'].quantile(0.0)
    end_date = weather['date'].quantile(0.2)
    interval = alt.selection_interval(
        encodings=['x'],
        init={'x': [start_date.isoformat(), end_date.isoformat()]}
    )
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:47:35