如何在Vega-Lite索引图中过滤索引点左侧历史数据?
实现Vega-Lite点击过滤折线数据的方案
核心思路
通过点击事件捕获目标日期,在数据转换阶段过滤掉该日期之前的所有数据,只保留选中日期及之后的折线部分。
具体步骤
修改选择器触发方式
把原示例中鼠标悬停的选择器改成点击触发的单值选择器,在selection配置里调整触发逻辑:"selection": { "index": { "type": "single", "fields": ["date"], "on": "click", "nearest": true, "empty": "none" } }nearest: true:确保点击时自动匹配最近的日期数据点empty: "none":未点击时保持选择器为空,方便后续过滤逻辑处理
添加数据过滤转换
在折线图的transform数组里新增filter转换,判断每条数据的日期是否大于等于选中日期,未点击时默认显示全部数据:"transform": [ // 新增过滤逻辑,放在重索引计算前 {"filter": "index.date == null || datum.date >= index.date"}, // 保留原有的重索引计算逻辑 {"joinaggregate": [{"op": "first", "field": "price", "as": "index_price"}], "groupby": ["symbol"]}, {"calculate": "datum.price / datum.index_price", "as": "indexed"} ]这里
index是定义的选择器名称,index.date为点击选中的目标日期,datum.date是当前数据点的日期,通过条件判断过滤掉选中日期之前的所有数据。适配辅助元素
原示例中的垂直索引线(rule标记)可保留,点击后它会定位到选中日期,帮助用户清晰识别过滤起始点。
关键代码片段参考
结合原示例结构,修改后的核心部分如下:
{ "data": {"url": "data/stocks.csv"}, "selection": { "index": { "type": "single", "fields": ["date"], "on": "click", "nearest": true, "empty": "none" } }, "transform": [ {"filter": "index.date == null || datum.date >= index.date"}, {"joinaggregate": [{"op": "first", "field": "price", "as": "index_price"}], "groupby": ["symbol"]}, {"calculate": "datum.price / datum.index_price", "as": "indexed"} ], "mark": "line", "encoding": { "x": {"field": "date", "type": "temporal"}, "y": {"field": "indexed", "type": "quantitative", "title": "Price (Indexed)"}, "color": {"field": "symbol", "type": "nominal"} }, "layer": [ {"mark": "line"}, { "mark": "rule", "encoding": { "x": {"field": "date", "type": "temporal", "selection": "index"} } } ] }
内容的提问来源于stack exchange,提问作者Martin Lam
相关产品推荐
相关产品推荐

