Echarts双Y轴刻度分割线对不齐问题

  • Post author:
  • Post category:其他


# Echarts双Y轴刻度分割线对不齐问题

>  [已发布Echarts社区点击查看](https://www.makeapie.com/editor.html?c=xdDYQAJSZA)


## 一、问题如图所示

![image.png](https://upload-images.jianshu.io/upload_images/9495732-dc06f25adeb41049.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

##

> 为了美观必须要去掉一个Y轴的分割线,然而去掉一条后数值跑偏对不上

![image.png](https://upload-images.jianshu.io/upload_images/9495732-064f989d05e75684.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

## 二、 计算Y轴最大值,基于最大值均分

##### 取出每一列最大值

> 在堆积图表中需要取出每一个X轴对应的多个series item的值,进行累计得出当前X轴最大值,最后取出所有X轴的最大值。如下图:


![image.png](https://upload-images.jianshu.io/upload_images/9495732-37f4a68cb6db85f3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

“`js

var series = [{


yAxisIndex: 0,

name: ‘直接访问’,

type: ‘bar’,

stack: ‘总量’,

data: [2, 2, 2, 2, 2, 2, 11]

}, {


yAxisIndex: 0,

name: ‘直接访问2’,

type: ‘bar’,

stack: ‘总量’,

data: [2, 2, 2, 2, 2, 2, 17]

}, {


name: ‘转化率’,

type: ‘line’,

data: [90, 60, 80, 30, 15, 68, 77],

yAxisIndex: 1

}]

const Y1Series = [];

const Y2Series = [];

let Y2Max = 0;

let Y1Max = 0;

series.forEach((item) => {


if (item.yAxisIndex === 0) {


Y1Series.push(item.data)

} else {


Y2Series.push(item.data)

}

})

/*

此时

Y1Series = [[2, 2, 2, 2, 2, 2, 11],[2, 2, 2, 2, 2, 2, 17]]

Y1Series = [90, 60, 80, 30, 15, 68, 77]

*/

/*

params { array }  [] => [[series.data],[series.data]],[series.data]]]

return number

*/

function getYaxisMax(seriesList) {


var res = [];

seriesList.forEach((item) => {


item.forEach((i, idx) => {


if (!res[idx]) {


if (isNaN(i / 1)) {


res[idx] = 0

} else {


res[idx] = i / 1

}

} else {


if (isNaN(i / 1)) {


res[idx] += 0

} else {


res[idx] += i / 1

}

}

})

});

return Math.max.apply(null, res)

}

Y1Max = getYaxisMax(Y1Series) // Y1轴最大值

Y2Max = getYaxisMax(Y2Series) // Y2轴最大值

“`

##### 如下图所示

> 现在虽然2个Y周的刻度分割线一致了,但是新的问题有来了

> 2条Y轴的刻度值,和刻度间隔值。存在小数,且间隔值并不是 5,50,10,100之类的数

![image.png](https://upload-images.jianshu.io/upload_images/9495732-e80a79fd9184cc87.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

### 三、解决刻度间隔值问题

“`js

// 刻度最大值

function yAxisMax(maxValue) {


if (isNaN(maxValue / 1) || maxValue / 1 < 10) {


return 10

}

const max = Math.ceil(maxValue) + ”;

const itemValue = Math.ceil(max / 5) + ”;

const mins = Math.ceil((itemValue / Math.pow(10, itemValue.length – 1)))

const item = mins * Math.pow(10, itemValue.length – 1) + ”;

// item 需要是5的整数倍

const res = Math.ceil(item / 5) * 5 * 5;

return res

}

“`

##### 最终效果

![image.png](https://upload-images.jianshu.io/upload_images/9495732-bc6159a0e396cd36.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![image.png](https://upload-images.jianshu.io/upload_images/9495732-b06ee1d7a289607e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

>  [已发布Echarts社区点击查看](https://www.makeapie.com/editor.html?c=xdDYQAJSZA)



版权声明:本文为wangjienull原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。