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

如何在Apache Echarts中沿X轴居中对齐图例项?

ECharts图例居中对齐实现方案

可以实现,直接通过配置legend的核心属性就能搞定,官方文档里有这个配置只是容易被忽略。针对你用的堆叠水平柱状图,提供两种可行方案:

方案一:直接设置图例项对齐属性

ECharts的legend配置里有align属性,专门控制图例项在容器内的对齐方式,默认值为'left',改成'center'即可让图例项居中。同时可以设置left和right为'auto',确保图例容器整体在图表顶部居中。

示例配置代码:

option = {
  legend: {
    orient: 'horizontal', // 保持横向布局,和默认一致
    align: 'center', // 关键配置:图例项居中对齐
    left: 'auto',
    right: 'auto',
    data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎'] // 替换为你的图例数据
  },
  // 以下保留你原有堆叠水平柱状图的配置
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value'
  },
  yAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  series: [
    {
      name: '直接访问',
      type: 'bar',
      stack: 'total',
      data: [320, 302, 301, 334, 390, 330, 320]
    },
    {
      name: '邮件营销',
      type: 'bar',
      stack: 'total',
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: '联盟广告',
      type: 'bar',
      stack: 'total',
      data: [220, 182, 191, 234, 290, 330, 310]
    },
    {
      name: '视频广告',
      type: 'bar',
      stack: 'total',
      data: [150, 212, 201, 154, 190, 330, 410]
    },
    {
      name: '搜索引擎',
      type: 'bar',
      stack: 'total',
      data: [820, 832, 901, 934, 1290, 1330, 1320]
    }
  ]
};

方案二:适配复杂图例场景

如果你的图例项数量较多需要换行,或者需要更精确的布局控制,可以让图例容器占满图表宽度,强制图例项在满宽容器内居中:

option = {
  grid: {
    top: 80, // 给图例留出足够顶部空间
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  legend: {
    orient: 'horizontal',
    align: 'center',
    left: 0,
    right: 0,
    width: '100%', // 让图例容器占满图表宽度
    data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
  },
  // 其他图表配置保留原有内容
};

测试后第一种方案就能满足常规需求,无需复杂自定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 15:58:11