找回密码
 立即注册
首页 业界区 业界 Echarts双Y轴,有负数情况下,0对齐实现

Echarts双Y轴,有负数情况下,0对齐实现

晁红叶 6 天前
效果如下图
1.png

 

 项目中遇到这个需求,需要支持负数情况下两侧0刻度对齐,且空白地方不能过多,且刻度值不要使用计算出来的随机数,使用整数
如果只是0刻度对齐正常设置:alignTicks:true 即可,版本需要5.3.0 才可,不过我的是5.4.3版本,却不生效,没找到原因,于是自己手写了适配,设置了min和max
这是我Y轴的配置
2.png

 下面是获取左侧和右侧最大值,和最小值方法
  1. const axisOpts = {};
  2.       if (hasNegative) {
  3.         // 左侧数据
  4.         const max0 = Math.max(...amountList);
  5.         const min0 = Math.min(...amountList);
  6.         // 右侧数据
  7.         const max1 = Math.max(...rateList);
  8.         const min1 = Math.min(...rateList);
  9.         // 计算比例
  10.         const range0 = max0 - min0;
  11.         const range1 = max1 - min1;
  12.         let ratio = 1;
  13.         if (range1 !== 0) {
  14.           ratio = range0 / range1;
  15.         }
  16.         // 计算左侧轴的临时范围,强制包含0
  17.         const Lmin = Math.min(min0, ratio * min1, 0);
  18.         const Lmax = Math.max(max0, ratio * max1, 0);
  19.         // 整齐化左侧轴的范围
  20.         const Lmin_nice = this.<em id="__mceDel">roundToNiceNumber</em>(Lmin, false);
复制代码
  1. <em id="__mceDel">        const Lmax_nice = this.roundToNiceNumber(Lmax, true);
  2.         // 计算右侧轴的范围
  3.         const Rmin_nice = Lmin_nice / ratio;
  4.         const Rmax_nice = Lmax_nice / ratio;
  5.         // 设置坐标轴选项
  6.         axisOpts.min = [Lmin_nice, Rmin_nice];
  7.         axisOpts.max = [Lmax_nice, Rmax_nice];
  8.       }</em>
复制代码
 
  1. roundToNiceNumber(value, isMax) {
  2.       if (value === 0) return 0;
  3.       const absValue = Math.abs(value);
  4.       const sign = value > 0 ? 1 : -1;
  5.       // 计算数量级
  6.       const exponent = Math.floor(Math.log10(absValue));
  7.       const fraction = absValue / Math.pow(10, exponent);
  8.       // 整齐的分数:1, 2, 5, 10 改为了 1,2,4,5,6,8
  9.       const breakpoints = [1, 2, 3, 4, 5, 6, 8, 9, 10];
  10.       const niceFraction = breakpoints.find(v => v >= fraction) || 10;
  11.       let niceValue = niceFraction * Math.pow(10, exponent) * sign;
  12.       // 根据是最大值还是最小值调整
  13.       if (isMax) {
  14.         if (value > 0) {
  15.           // 对于最大值,向上取整到niceValue的整数倍
  16.           niceValue = Math.ceil(value / niceValue) * niceValue;
  17.         } else {
  18.           // 对于负数的最大值,向下取整(因为负数越大,绝对值越小)
  19.           niceValue = Math.floor(value / niceValue) * niceValue;
  20.         }
  21.       } else {
  22.         if (value > 0) {
  23.           // 对于正数的最小值,向下取整
  24.           niceValue = Math.floor(value / niceValue) * niceValue;
  25.         } else {
  26.           // 对于负数的最小值,向上取整
  27.           niceValue = Math.ceil(value / niceValue) * niceValue;
  28.         }
  29.       }
  30.       return niceValue;
  31.     },
复制代码
  上面是配置的计算min,max设置值的方法

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册