如何在含repeat配置的Vega-Lite图例上启用鼠标点击事件?
解决Vega-Lite Repeat配置下Params绑定图例的重复信号错误
当你用repeat.layer生成多图层时,直接在子spec中定义绑定图例的params会导致每个图层都创建同名信号,触发重复信号错误。解决思路是把交互参数移到顶层配置,统一管理信号,避免重复定义。
以下是修正后的完整配置:
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": {"url": "data/movies.json"}, "params": [ { "name": "toggleSeries", "select": {"type": "point", "fields": ["series"], "toggle": true}, "value": [{"series": "US Gross"}, {"series": "Worldwide Gross"}] } ], "repeat": {"layer": ["US Gross", "Worldwide Gross"]}, "spec": { "mark": "line", "encoding": { "x": {"bin": true, "field": "IMDB Rating", "type": "quantitative"}, "y": { "aggregate": "mean", "field": {"repeat": "layer"}, "type": "quantitative", "title": "Mean of US and Worldwide Gross" }, "color": { "datum": {"repeat": "layer"}, "type": "nominal", "legend": {"title": "Gross Type"} }, "opacity": { "condition": {"param": "toggleSeries", "test": "indexof(datum.series, repeat('layer')) !== -1", "value": 1}, "value": 0.1 } } }, "config": { "legend": {"bind": "toggle"} } }
关键改动说明:
- 顶层定义
toggleSeries参数,统一管理系列的选中状态,避免repeat重复生成信号 - 用
opacity编码的condition判断当前系列是否在选中参数中,控制显示/隐藏 - 顶层
config中设置legend.bind: toggle,让图例直接绑定顶层参数,实现点击图例切换系列可见性
内容的提问来源于stack exchange,提问作者Raghav Khare
相关产品推荐
相关产品推荐

