背景:当设置双轴的时候,轴线的刻度数量、间距均由echart内部自动计算,导致两边的轴线大概率下不会对齐,如下图所示:
查询echarts配置文档,发现以下属性:
min: 坐标轴刻度最小值
max: 坐标轴刻度最大值
splitNumber:坐标轴的分割段数
interval:强制设置坐标轴分割间隔
OK,我们根据业务数据,定制化的计算相关属性值即可。
options.yAxis.forEach((y, index) => {
// leftMax, rightMax的值,请自行根据自身数据计算,即:默认配置下的最大值
// const { leftMax, rightMax} = this.getMaxValue();
// index === 0时是左轴,1是右轴
let max = !index ? rightMax + '' : leftMax + '';
max = value === 'null' ? 0 : this.computeMax(max);
y.splitNumber = SPLIT_NUMBER;
y.interval = max / SPLIT_NUMBER;
y.max = max;
});
const SPLIT_NUMBER = 4; // 分割段数
/**
* @description 根据实际最大值,计算轴的最大值
* @param { String} value 实际的最大值(字符串的数字)
* @returns { Number } 计算后的最大值
*/
computeMax(value) {
if (Math.floor(value) === 0) { // 是小数
let { result, digit } = getNumberFromDecimal(Number(value));
result = result.substr(0, 2); // 取前两位
return Number(Math.ceil(value / SPLIT_NUMBER) * SPLIT_NUMBER) / Math.pow(10, digit - 1 + 2);
} else {
const roundValue = Math.floor(value).toString();
if (roundValue.length > 2) { // 两位以上
const topTwo = roundValue.substr(0, 2);
const len = roundValue.length;
return Number(Math.ceil(topTwo / SPLIT_NUMBER) * SPLIT_NUMBER) * Math.pow(10, len - 2);
} else {
return Number(Math.ceil(value / SPLIT_NUMBER) * SPLIT_NUMBER);
}
}
}
/**
* @description 获取小于0的小数中的数字
* @param { Number } decimal 小数
* @returns { result, digit } 小数点后不包括0的数字,小数点后的位数
*/
getNumberFromDecimal = function(decimal) {
let str = decimal.toString();
if (typeof decimal !== 'number' || !str.includes('.')) {
throw '参数不是小数';
}
if (decimal >= 1) {
throw '参数大于等于1';
}
for (let i = 0; i < str.length; i ++) {
if (str[i] !== '0' && str[i] !== '.') {
return { result: str.substring(i, str.length), digit: i - 2 };
}
}
}
思路大致如上, 具体可根据自身业务做相应的调整。
附上最后效果图: