阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > 图例(Legend)配置

图例(Legend)配置

作者:陈川 阅读数:61683人阅读 分类: ECharts

图例(Legend)基础概念

图例是数据可视化图表中用于说明不同系列或类别对应样式的组件。在ECharts中,图例通过视觉符号(如颜色、形状)和文本标签帮助用户理解图表数据的分类关系。图例可以水平或垂直排列,支持交互行为如点击筛选系列。

option = {
  legend: {
    data: ['销量', '库存', '订单']
  },
  xAxis: { type: 'category', data: ['Q1', 'Q2', 'Q3', 'Q4'] },
  yAxis: { type: 'value' },
  series: [
    { name: '销量', type: 'bar', data: [120, 200, 150, 80] },
    { name: '库存', type: 'bar', data: [85, 120, 135, 70] },
    { name: '订单', type: 'line', data: [65, 100, 120, 90] }
  ]
};

图例位置与布局

通过top/bottom/left/right属性控制图例在容器中的位置,支持百分比和像素值。orient属性定义排列方向(horizontal/vertical),itemGap设置图例项间距。

legend: {
  orient: 'vertical',
  right: 10,
  top: 'center',
  itemGap: 20,
  data: ['邮件营销','联盟广告','视频广告']
}

图例样式定制

textStyle配置文本样式,itemWidthitemHeight控制图例标记尺寸。itemStyle定义图例图形样式,支持富文本格式:

legend: {
  textStyle: {
    color: '#333',
    fontSize: 14,
    fontWeight: 'bold'
  },
  itemWidth: 25,
  itemHeight: 14,
  itemStyle: {
    borderWidth: 2,
    borderColor: '#c23531'
  }
}

图例交互功能

selectedMode启用选择模式(single/multiple),selected预设选中状态。通过formatter函数动态生成文本:

legend: {
  selectedMode: 'multiple',
  selected: { '销量': false },
  formatter: function(name) {
    return '【' + name + '】';
  }
}

分页图例配置

当图例项过多时,启用type: 'scroll'实现分页浏览。通过pageButtonItemGap控制翻页按钮间距,pageButtonPosition设置按钮位置:

legend: {
  type: 'scroll',
  pageIconColor: '#2f4554',
  pageIconInactiveColor: '#aaa',
  pageTextStyle: { color: 'black' },
  pageButtonItemGap: 5
}

自定义图例内容

通过data数组定义图例项时,可单独设置每个项目的样式和图标。使用icon属性指定自定义图形:

legend: {
  data: [
    { 
      name: '搜索引擎',
      icon: 'path://M10,10 L20,10 L20,20 L10,20 Z',
      textStyle: { color: 'red' }
    },
    {
      name: '直接访问',
      icon: 'circle'
    }
  ]
}

图例与系列联动

图例与系列数据自动关联,当系列name与图例data匹配时显示对应图例项。动态数据场景下可通过setOption更新:

myChart.setOption({
  legend: { data: newLegendData },
  series: newSeriesData
});

特殊类型图例

对于饼图等特殊图表,图例可显示数值百分比。通过legend.formatter结合回调参数实现:

legend: {
  formatter: function(name) {
    const data = option.series[0].data;
    const item = data.find(item => item.name === name);
    return `${name} (${item.value}%)`;
  }
}

图例事件处理

绑定图例点击事件实现自定义交互。ECharts提供legendselectchanged事件:

myChart.on('legendselectchanged', function(params) {
  console.log('选中的图例:', params.selected);
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌