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

如何实现ECharts自定义图例标签与值两端对齐?

解决ECharts图例标签与数值两端对齐问题

要实现图例标签与数值的两端对齐(类似CSS flex布局的justify-between效果),核心是给图例的富文本容器设置固定宽度,再分别对标签和数值设置左右对齐。以下是修改后的完整实现代码:

修改后的JavaScript代码

var dom = document.getElementById('chart-container');
var myChart = echarts.init(dom, 'dark', {
  renderer: 'canvas',
  useDirtyRect: false
});
var app = {};

var option;

const dataList = [
  { value: 1048, name: 'Search Engine', count: 245 },
  { value: 735, name: 'Direct', count: 56 },
  { value: 580, name: 'Email', count: 45 },
  { value: 484, name: 'Union Ads', count: 21 },
  { value: 300, name: 'Video Ads', count: 54 }
];

// 动态计算容器宽度,适配最长标签
const maxLabelWidth = Math.max(...dataList.map(item => item.name.length)) * 14;

option = {
  title: {
    text: 'Referer of a Website',
    subtext: 'Fake Data',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    formatter: function (name) {
      const count = dataList.find(a => a.name === name).count;
      return `{container|{name|${name}}{count|${count}}}`;
    },
    textStyle: {
      rich: {
        container: {
          width: maxLabelWidth + 50, // 容器宽度=最长标签宽度+数值预留空间
          align: 'justify'
        },
        name: {
          align: 'left'
        },
        count: {
          align: 'right',
          color: 'red',
          padding: [0, 0, 0, 10]
        }
      }
    }
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: '50%',
      data: dataList,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

if (option && typeof option === 'object') {
  myChart.setOption(option);
}

window.addEventListener('resize', myChart.resize);

关键修改说明

  1. 动态容器宽度:计算最长标签的宽度,确保容器能容纳所有标签和数值,避免内容挤压
  2. 富文本容器:新增container样式块,设置固定宽度并启用两端对齐
  3. 独立对齐设置:标签设为左对齐,数值设为右对齐,配合容器宽度实现两端分布

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:31:21