如何为Vega-Lite多系列折线图添加tooltip交互提示
实现思路
- 你当前使用repeat语法生成多系列折线,只需在encoding配置中新增tooltip字段,绑定需要展示的日期、汽油品类、对应价格三类信息即可实现基础悬浮提示
- 如需优化交互体验,可新增一个x轴时间维度的选择器,实现鼠标悬停到任意时间点时,一次性展示该时间点所有品类的价格,无需逐根折线触发提示
修改后代码
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "description": "1996-2020年不同品类汽油价格折线图", "width": 720, "height": 480, "padding": 5, "data": { "name": "gas_prices", "url": "data/testInfo.csv", "format": {"type": "csv", "parse": {"A1": "number", "date": "date"}} }, "repeat": { "layer": ["A1","A2","A3","R1","R2","R3","M1","M2","M3","P1","P2","P3","D1"] }, "spec": { // 新增point配置,方便触发悬浮交互 "mark": {"type": "line", "point": true}, // 新增选择器配置,实现按时间点批量触发tooltip,不需要可删除 "selection": { "hover": { "type": "single", "on": "pointerover", "fields": ["date"], "nearest": true, "empty": "none" } }, "encoding": { "x": { "timeUnit": "yearmonth", "title": "Date", "field": "date" }, "y": { "field": {"repeat":"layer"}, "title": "Gas Prices", "type": "quantitative" }, "color": { "datum": {"repeat": "layer"}, "type": "nominal", "title": "汽油品类" }, // 新增tooltip配置 "tooltip": [ {"timeUnit": "yearmonth", "field": "date", "title": "日期"}, {"datum": {"repeat": "layer"}, "type": "nominal", "title": "汽油品类"}, {"field": {"repeat": "layer"}, "type": "quantitative", "title": "价格"} ] } } }
学习资源推荐
- 优先查看Vega-Lite官方文档中Tooltip、交互选择器、Repeat语法三个模块的参数说明,所有属性的作用范围都有明确标注
- 可在国内技术社区搜索Vega-Lite多图表交互实战类教程,参考现成案例快速熟悉语法
内容的提问来源于stack exchange,提问作者noobie
相关产品推荐
相关产品推荐

