如何在Vega-Lite中切换数组内对象数据实现下拉筛选功能
实现方案
方案1:外置JS控制(最易上手,适配现有代码)
无需修改现有Vega-Lite配置的核心结构,直接通过JS监听下拉菜单的选择事件,切换数据集后重新渲染图表即可:
- 页面添加下拉选择器和图表容器
<select id="schoolSelector"> <option value="0">学校A</option> <option value="1">学校B</option> <!-- 新增学校只需加option,value对应test1的索引即可 --> </select> <div id="pieChart"></div>
- 改写JS逻辑绑定切换事件
// 原有测试数据 var test1 = [ [{ "name": "Piece One", "amount": 5 }, { "name": "Piece Two", "amount": 5 }, { "name": "Piece Three", "amount": 5 }], [{ "name": "Piece One", "amount": 1 }, { "name": "Piece Two", "amount": 1 }, { "name": "Piece Three", "amount": 5 }] ]; // 初始图表配置 var pieCreate = { "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "title": "A pie chart", "description": "A simple pie chart with embedded data.", "width": "container", "height": "container", "data": { "values": test1[0] }, "mark": "arc", "encoding": { "theta": { "field": "amount", "type": "quantitative" }, "color": { "field": "name", "type": "nominal", "legend": null } } }; // 初始渲染图表 vegaEmbed('#pieChart', pieCreate).then(result => window.view = result.view); // 监听下拉切换事件 document.getElementById('schoolSelector').addEventListener('change', e => { const selectedIndex = parseInt(e.target.value); // 切换对应数据集 pieCreate.data.values = test1[selectedIndex]; // 重新渲染 vegaEmbed('#pieChart', pieCreate).then(result => window.view = result.view); })
方案2:Vega-Lite内置参数实现(无需外置重渲染逻辑)
如果希望所有交互逻辑都封装在Vega-Lite配置内,可以直接传入全量数据,加一个下拉选择参数过滤数据即可:
var pieCreate = { "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "title": "A pie chart", "description": "A simple pie chart with embedded data.", "width": "container", "height": "container", // 配置下拉选择参数,等价于你之前想实现的signal功能 "params": [ { "name": "selectedSchool", "value": 0, "bind": { "input": "select", "options": [0,1], "labels": ["学校A", "学校B"] } } ], "data": { // 把全量数据扁平化,新增schoolIndex字段标记所属学校的索引 "values": test1.flatMap((item, index) => item.map(d => ({...d, schoolIndex: index}))) }, // 按选中的学校索引过滤数据 "transform": [ {"filter": "datum.schoolIndex == selectedSchool"} ], "mark": "arc", "encoding": { "theta": { "field": "amount", "type": "quantitative" }, "color": { "field": "name", "type": "nominal", "legend": null } } }; // 直接渲染即可,下拉菜单会自动生成在图表上方 vegaEmbed('#pieChart', pieCreate)
内容的提问来源于stack exchange,提问作者RichmondMJ
相关产品推荐
相关产品推荐

