You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改ECharts图例选中事件?实现点击时系列不消失仅变暗

实现ECharts图例点击后系列淡化而非隐藏的效果

问题场景

默认点击ECharts图例项时,对应系列会直接从图表中消失(比如点击「Video Ads」后黄色线条完全隐藏),但需要实现类似emphasis: {focus: 'series'}的交互逻辑——点击图例后目标系列不消失,仅变为淡化状态。

解决方案

通过关闭图例默认的隐藏功能,手动监听图例点击事件,控制对应系列的透明度来实现需求:

  • 关闭图例默认隐藏行为:设置legend.selectedMode: false,阻止点击图例时自动隐藏系列。
  • 监听图例点击事件:捕获点击的图例名称,切换对应系列的透明度。
  • 维护图例选中状态:手动更新图例的选中样式,让用户直观看到当前状态。

代码示例

// 初始化图表实例
const myChart = echarts.init(document.getElementById('main'));

// 基础配置
const baseOption = {
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine'],
    selectedMode: false, // 禁用默认的选中/隐藏逻辑
    selected: {
      // 初始状态所有系列都处于正常显示状态
      'Email': true,
      'Union Ads': true,
      'Video Ads': true,
      'Direct': true,
      'Search Engine': true
    }
  },
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    { name: 'Email', type: 'line', data: [120, 132, 101, 134, 90, 230, 210], lineStyle: { opacity: 1 } },
    { name: 'Union Ads', type: 'line', data: [220, 182, 191, 234, 290, 330, 310], lineStyle: { opacity: 1 } },
    { name: 'Video Ads', type: 'line', data: [150, 232, 201, 154, 190, 330, 410], lineStyle: { opacity: 1 } },
    { name: 'Direct', type: 'line', data: [320, 332, 301, 334, 390, 330, 320], lineStyle: { opacity: 1 } },
    { name: 'Search Engine', type: 'line', data: [820, 932, 901, 934, 1290, 1330, 1320], lineStyle: { opacity: 1 } }
  ]
};

myChart.setOption(baseOption);

// 监听图例点击事件
myChart.on('legendselectchanged', (params) => {
  const targetSeriesName = params.name;
  // 切换当前图例的选中状态
  const newSelectedState = !params.selected[targetSeriesName];

  // 更新图例选中状态
  myChart.setOption({
    legend: {
      selected: {
        [targetSeriesName]: newSelectedState
      }
    }
  });

  // 更新对应系列的透明度(线条和标记点同步处理)
  const updatedSeries = myChart.getOption().series.map(series => {
    if (series.name === targetSeriesName) {
      return {
        ...series,
        lineStyle: {
          opacity: newSelectedState ? 1 : 0.2 // 正常状态100%不透明,淡化状态20%不透明
        },
        itemStyle: {
          opacity: newSelectedState ? 1 : 0.2
        }
      };
    }
    return series;
  });

  myChart.setOption({ series: updatedSeries });
});

补充说明

  • 可以调整opacity的数值(比如0.3、0.1)来控制淡化的程度,适配不同视觉需求。
  • 如果是柱状图、饼图等其他图表类型,只需将lineStyle替换为对应图表的样式属性(比如柱状图的itemStyle)即可。
  • 代码支持多图例点击切换,每次点击只会改变当前选中图例对应系列的状态。

内容的提问来源于stack exchange,提问作者Nosty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:38:40