如何配置ECharts dataZoom滑块以选择预定义离散值
实现DataZoom滑块基于预定义离散值过滤数据
需求说明
想用ECharts的dataZoom滑块过滤数据,但限制用户只能从预定义的离散值(比如0到100的整数)中选择,而非基于绘制曲线的series.data数据。
当前代码
chart.setOption({ xAxis: { splitLine: false, axisLabel: { show: false }, axisTick: { show: false } }, yAxis: { axisLabel: false, axisTick: false, splitLine: false }, dataZoom: [ { type: "slider", id: 'magnitude', show: true, xAxisIndex: [0], height: sliderHeight, bottom: 8, realtime: false } ], series: [ { data: <data>, type: "line", smooth: true, showSymbol: false, itemStyle: { color: defaultColor }, areaStyle: { color: defaultColor } } ] })
注:<data>为曲线点坐标的二维数组,当前效果如图:
实现方案
核心思路是让x轴绑定预定义离散值,再通过dataZoom事件监听获取选中范围,最后过滤业务数据并更新图表:
定义离散值数组
创建你需要的预定义离散值集合,比如0到100的整数:const discreteValues = Array.from({length: 101}, (_, index) => index);修改xAxis配置
将x轴的data设置为上面定义的离散值数组,让dataZoom滑块基于这些值生效:xAxis: { splitLine: false, axisLabel: { show: false }, axisTick: { show: false }, data: discreteValues // 绑定离散值 },监听dataZoom事件并过滤数据
给图表添加datazoom事件监听,当滑块变动时,获取选中的离散值范围,过滤业务数据后更新series:// 假设originalData是你的原始业务数据,每个项包含对应离散值的字段(比如value) chart.on('datazoom', (params) => { if (params.batch[0].dataZoomId === 'magnitude') { // 获取滑块选中的起始/结束离散值 const startValue = discreteValues[params.batch[0].start]; const endValue = discreteValues[params.batch[0].end]; // 过滤原始数据 const filteredData = originalData.filter(item => { return item.value >= startValue && item.value <= endValue; }); // 更新图表数据 chart.setOption({ series: [{ data: filteredData }] }); } });调整dataZoom步进(可选)
为了让滑块移动更贴合离散值,设置step属性为1:dataZoom: [ { type: "slider", id: 'magnitude', show: true, xAxisIndex: [0], height: sliderHeight, bottom: 8, realtime: false, step: 1 // 强制滑块每次移动1个离散值单位 } ]
完整示例代码
// 定义预定义离散值 const discreteValues = Array.from({length: 101}, (_, index) => index); // 假设原始业务数据 const originalData = [...]; // 你的原始数据集合 const chart = echarts.init(document.getElementById('chart')); chart.setOption({ xAxis: { splitLine: false, axisLabel: { show: false }, axisTick: { show: false }, data: discreteValues }, yAxis: { axisLabel: false, axisTick: false, splitLine: false }, dataZoom: [ { type: "slider", id: 'magnitude', show: true, xAxisIndex: [0], height: 20, bottom: 8, realtime: false, step: 1 } ], series: [ { data: originalData, type: "line", smooth: true, showSymbol: false, itemStyle: { color: '#1890ff' }, areaStyle: { color: '#1890ff' } } ] }); // 监听dataZoom事件过滤数据 chart.on('datazoom', (params) => { if (params.batch[0].dataZoomId === 'magnitude') { const startValue = discreteValues[params.batch[0].start]; const endValue = discreteValues[params.batch[0].end]; const filteredData = originalData.filter(item => { // 根据你的数据结构调整判断逻辑 return item.value >= startValue && item.value <= endValue; }); chart.setOption({ series: [{ data: filteredData }] }); } });
内容的提问来源于stack exchange,提问作者zephyrus
相关产品推荐
相关产品推荐

