例一:
<div id="main" style="width: 700px;height:600px;"></div>
<script src="https://cdn.bootcss.com/echarts/4.7.0/echarts.min.js"></script>
<script>
const myChart = echarts.init(document.getElementById('main'));
/*
* data1 销售量的系列数据
* data2 盈利额的系列数据
*/
const data1 = [15, 12, 16, 11, 16, 20];
const data2 = [-150, 120, 160, -110, 160, 200];
//理想行数(实际行数会有浮动)
const rowNum = 6;
/*数据极值
* max1 销售量数据的最大值
* max2 盈利额数据的最大值
* min1 销售量数据的最小值
* min2 盈利额数据的最小值
* */
let max1 = Math.max(...data1);
let max2 = Math.max(...data2);
let min1 = Math.min(...data1);
let min2 = Math.min(...data2);
/*极值比例*/
const rat1 = min1 / max1;
const rat2 = min2 / max2;
/*比例大小对比*/
const ratState = rat1 > rat2;
/*设置极小值*/
if (ratState) {
min1 = rat2 * max1;
} else {
min2 = rat1 * max2;
}
/*
* inter1 销售量的行高取整
* inter2 盈利额的行高取整
* */
let inter1 = Math.ceil((max1 - min1) / rowNum);
let inter2 = Math.ceil((max2 - min2) / rowNum);
/*对极值微调*/
min1 = Math.floor(min1 / inter1) * inter1;
max1 = Math.ceil(max1 / inter1) * inter1;
min2 = Math.floor(min2 / inter2) * inter2;
max2 = Math.ceil(max2 / inter2) * inter2;
/*配置项*/
const option = {
tooltip: {},
legend: {
data: ['销售量', '盈利额']
},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
},
yAxis: [{
type: 'value',
scale: true,
name: '销售量',
min: min1,
max: max1,
interval: inter1,
},
{
type: 'value',
scale: true,
name: '盈利额',
min: min2,
max: max2,
interval: inter2,
}
],
series: [{
name: '销售量',
type: 'bar',
yAxisIndex: 0,
data: data1,
},
{
name: '盈利额',
type: 'bar',
yAxisIndex: 1,
data: data2
}
]
};
myChart.setOption(option);
</script>
let leftArr = [1,2,3,4,5,6] // 显示在左边数据集合
let rightArr = [2,3,4,5,6,7] // 显示在右边数据集合
let leftMax = Math.max.apply(null, leftArr); // 获取左边y轴数组的最大值
let rightMax = Math.max.apply(null, rightArr); // 获取右边y轴数组的最大值
let yMax = Math.max(leftMax, rightMax); // 获取两个最大值之中的最大值
// 如果%10有余数,这说明不是十的倍数,则修改成整十的倍数
if((yMax % 10) != 0) yMax = yMax + (10 - (yMax % 10))
if(yMax == 0) yMax = null
yAxis: [
{
type: 'value',
min: 0,
max: yMax
}, {
type: 'value',
min: 0,
max: yMax
}
],