当eachars的y轴左右两侧不对齐时
前端|echarts
发布于2023-04-06 最近修改2023-04-06
669
0
Shimmer
javascript
复制代码
/** * @description 获取小于0的小数中的数字 * @param { Number } decimal 小数 * @returns { result, digit } 小数点后不包括0的数字,小数点后的位数 */ const getNumberFromDecimal = (decimal) => { const str = decimal.toString(); if (typeof decimal !== 'number' || !str.includes('.')) { // eslint-disable-next-line @typescript-eslint/no-throw-literal throw '参数不是小数'; } if (decimal >= 1) { // eslint-disable-next-line @typescript-eslint/no-throw-literal throw '参数大于等于1'; } for (let i = 0; i < str.length; i += 1) { if (str[i] !== '0' && str[i] !== '.') { return { result: str.substring(i, str.length), digit: i - 2 }; } } return null; }; const SPLIT_NUMBER = 4; // 分割段数 /** * @description 根据实际最大值,计算轴的最大值 * @param { String} value 实际的最大值(字符串的数字) * @returns { Number } 计算后的最大值 */ const computeMax = (value) => { if (Math.floor(value) === 0) { // 是小数 // eslint-disable-next-line prefer-const let { result, digit } = getNumberFromDecimal(Number(value)) as any; // eslint-disable-next-line @typescript-eslint/no-unused-vars result = result.substr(0, 2); // 取前两位 // eslint-disable-next-line no-restricted-properties return Number(Math.ceil(value / SPLIT_NUMBER) * SPLIT_NUMBER) / Math.pow(10, digit - 1 + 2); } const roundValue = Math.floor(value).toString(); if (roundValue.length > 2) { // 两位以上 const topTwo = +roundValue.substr(0, 2); const len = roundValue.length; // eslint-disable-next-line no-restricted-properties return Number(Math.ceil(topTwo / SPLIT_NUMBER) * SPLIT_NUMBER) * Math.pow(10, len - 2); } return Number(Math.ceil(value / SPLIT_NUMBER) * SPLIT_NUMBER); }; const getMaxValue = () => { const yList1 = _.cloneDeep(data) .sort((a, b) => b.totalCount - a.totalCount) .map((item) => item.totalCount); const yList2 = _.cloneDeep(data) .sort((a, b) => b.money - a.money) .map((item) => item.money); return { leftMax: yList1[0], rightMax: yList2[0], }; }; option.yAxis.forEach((y: any, index) => { // leftMax, rightMax的值,请自行根据自身数据计算,即:默认配置下的最大值 const { leftMax, rightMax } = getMaxValue(); // index === 0时是左轴,1是右轴 let max = index ? rightMax : leftMax; max = max === null ? 0 : computeMax(max); // eslint-disable-next-line no-param-reassign y.splitNumber = SPLIT_NUMBER; // eslint-disable-next-line no-param-reassign y.interval = max / SPLIT_NUMBER; // eslint-disable-next-line no-param-reassign y.max = max; }); chartDom.setOption(option);
目录