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

如何使用Altair为日期轴折线图添加双端滑块筛选器

为Altair折线图添加日期双端滑块筛选器

实现步骤

  • 确定日期边界:从DataFrame中提取date_x的最小和最大日期,作为滑块的取值范围
  • 创建滑块绑定:用alt.binding_range分别生成起始、结束日期的滑块,设置日期显示格式为YYYY-MM-DD
  • 添加滑块选择器:将滑块绑定到对应选择器,初始化值设为数据的首尾日期
  • 整合过滤逻辑:在transform_filter中同时应用指标选择过滤和日期范围过滤

修改后的完整代码

import pandas as pd
import altair as alt

data = {
    'Adj Close': [1.308934, 2.169581, 2.876765, 2.357847, 2.179156],
    'Yahoo Finance return': [0.670226, 1.298566, 0.920492, -0.721652, -0.306659],
    'date_x': ['2015-01-01', '2015-02-01', '2015-03-01', '2015-04-01', '2015-05-01'],
    'Return in USD': [-0.641970, 0.428617, 0.404568, 0.125614, 0.070045]
}

# 转换为DataFrame并处理日期格式
df = pd.DataFrame(data)
df['date_x'] = pd.to_datetime(df['date_x'])

# 数据重塑
final_melted = df.melt(id_vars=['date_x'], var_name='Metric', value_name='Value')

# 保留原有指标选择器逻辑
selection_metric_1 = alt.binding_select(options=['Adj Close', 'None','Yahoo Finance return',  'Return in USD'], name='Metric 1 ')
select_metric_1 = alt.selection_single(fields=['Metric'], bind=selection_metric_1, name="Selector 1")

selection_metric_2 = alt.binding_select(options=['Adj Close','None', 'Yahoo Finance return',  'Return in USD'], name='Metric 2 ')
select_metric_2 = alt.selection_single(fields=['Metric'], bind=selection_metric_2, name="Selector 2")

selection_metric_3 = alt.binding_select(options=['Adj Close','None', 'Yahoo Finance return', 'Return in USD'], name='Metric 3 ')
select_metric_3 = alt.selection_single(fields=['Metric'], bind=selection_metric_3, name="Selector 3")

# 获取日期范围,设置滑块边界
min_date = df['date_x'].min()
max_date = df['date_x'].max()

# 创建日期滑块绑定(step设为一天的毫秒数,确保按天步进)
start_date_binding = alt.binding_range(
    min=min_date,
    max=max_date,
    step=86400000,
    format='%Y-%m-%d',
    name='起始日期: '
)
end_date_binding = alt.binding_range(
    min=min_date,
    max=max_date,
    step=86400000,
    format='%Y-%m-%d',
    name='结束日期: '
)

# 初始化日期选择器
select_start_date = alt.selection_single(fields=['date_x'], bind=start_date_binding, name='Date', init={'date_x': min_date})
select_end_date = alt.selection_single(fields=['date_x'], bind=end_date_binding, name='Date', init={'date_x': max_date})

# 折线图层
line_chart = alt.Chart(final_melted).mark_line().encode(
    x='date_x:T',
    y=alt.Y('Value:Q', axis=alt.Axis(title='Metric Value')),
    color='Metric:N'
)

# 散点图层(支持hover提示)
points = alt.Chart(final_melted).mark_point().encode(
    x='date_x:T',
    y='Value:Q',
    color='Metric:N',
    tooltip=['date_x:T', 'Value:Q', 'Metric:N']
).properties(
    width=1600,
    height=800
)

# 整合图层与筛选逻辑
filtered_chart = alt.layer(line_chart, points).add_selection(
    select_metric_1,
    select_metric_2,
    select_metric_3,
    select_start_date,
    select_end_date
).transform_filter(
    # 同时满足:至少选中一个指标,且日期在滑块范围内
    (select_metric_1 | select_metric_2 | select_metric_3) &
    (alt.datum.date_x >= select_start_date.date_x) &
    (alt.datum.date_x <= select_end_date.date_x)
).interactive()

# 图表样式配置
configured_chart = filtered_chart.configure_axis(
    titleFontSize=15,
    labelFontSize=15
).configure_legend(
    titleFontSize=17,
    labelFontSize=15
).configure_title(
    fontSize=24
)

# 渲染图表
configured_chart

关键细节说明

  • 滑块step设为86400000(一天的毫秒数),确保拖动时按自然日切换日期
  • 初始值设为数据首尾日期,默认显示全量数据
  • 过滤逻辑加入指标选择判断,避免无选中指标时显示空图表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:33:30