ECharts Y轴大数值格式化与单位简写实现

作者:百宝袋时间:2026-10-31 16:55:26浏览:529

本文介绍在ECharts中处理Y轴过大数值的方法,通过自定义formatter函数结合toBMK工具函数,实现K、M、B等单位简写及百分比符号自动追加。示例代码展示了如何配置axisLabel以优化图表可读性,适用于大数据量可视化场景。

ECharts Y轴大数值格式化与单位简写实现

在绘制图表时,若Y轴显示的数值过大,直接展示会导致视觉拥挤或难以阅读,因此通常需要进行简化处理,例如转换为K、M等单位,或针对包含百分比的数据进行特殊格式化处理,具体效果可参考下图所示:

ECharts Y轴大数值格式化与单位简写实现

ECharts Y轴大数值格式化与单位简写实现

 yAxis: {
   type: 'value',

   // Y轴轴线
   axisLine: { show: false }, 

   // 刻度线
   axisTick: { show: false },

   // 轴刻度值
   axisLabel: {
     interval: 0, //坐标轴值与坐标轴间距

     rotate: 0, //旋转角度
    
     // 值格式化 (toBMK函数 处理 Y轴数字值)
     formatter(val) {
       return `${toBMK(val)}${option.series[0].data[0].indexOf('%') > -1 ? '%' : ''}`;
     },
   },
 }

图中红框标注的数值显示逻辑如下:

1K1000
1M1000,000
1B

1000,000,000

1KB1000,000,000,000

核心处理函数toBMK的定义如下:

export function toBMK(value) {
  const vblValue = Math.abs(value);
  const newValue = ['', '', ''];
  let fr = 1000;
  let num = 3;
  while (vblValue / fr >= 1) {
    fr *= 10;
    num += 1;
  }
  if (num <= 4) {
    newValue[1] = 'K';
    newValue[0] = vblValue / 1000 >= 10 
    ? `${parseInt(vblValue / 1000, 10)}` 
    : (vblValue / 1000).toFixed(1);

  } else if (num <= 7) {
    const text1 = parseInt(num - 3, 10) / 3 > 1 ? 'M' : 'K';
    const fm = text1 === 'K' ? 1000 : 1000000;
    newValue[1] = text1;
    newValue[0] = `${vblValue / fm}`;
  } else {
    let text1 = (num - 6) / 3 > 1 ? 'B' : 'M';
    text1 = (num - 9) / 3 > 1 ? 'KB' : text1;
    let fm = 1;
    if (text1 === 'M') {
      fm = 1000000;
    } else if (text1 === 'B') {
      fm = 1000000000;
    } else if (text1 === 'KB') {
      fm = 1000000000000;
    }
    newValue[1] = text1;
    newValue[0] = `${parseInt(vblValue / fm, 10)}`;
  }
  if (vblValue < 1000) {
    newValue[1] = '';
    newValue[0] = `${vblValue}`;
  }
  return `${value < 0 ? '-' : ''}${newValue.join('')}`;
}

在ECharts的Y轴配置中,通过yAxis属性下的axisLabel设置formatter回调函数,利用toBMK处理原始数值,即可将大数值自动转换为简写格式,使图表呈现更加美观简洁。

总结

以上就是关于ECharts坐标轴刻度数值处理的详细介绍,更多相关ECharts坐标轴刻度数值内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

作者最新文章