<template>
<v-app>
<v-main>
<v-row>
<v-col cols="12">
<v-card height="600" class="ml-3 mt-3" flat>
<div id="manyYAxisChart" style="height: 100%;width: 100%" class="mychart"></div>
</v-card>
</v-col>
</v-row>
</v-main>
</v-app>
</template>
<script>
export default {
name: "EchartsManyYAxis",
mounted() {
this.drawManyYAxisChart();
},
methods: {
drawManyYAxisChart(){
//随机数生成
// const a = Math.floor(Math.random() * (max - min + 1)) + min;
//随机生成多个Y轴的数据
let allData = [];
//i为多少个Y轴的数据
for (let i=0; i<9; i++){
allData[i]=[];
// j是有多少条数据
for (let j=0; j<15; j++){
let randomNum
if (j === 0){
randomNum = Math.floor(Math.random() * (300 - 1 + 1)) + 1;
} else {
randomNum = Math.floor(Math.random() * (100 - 1 + 1)) + 1;
}
// let randomNum = Math.floor(Math.random() * (100 - 1 + 1)) + 1;
allData[i][j] = [j,randomNum]
}
}
console.log(allData);
let myChart = this.$echarts.init(document.getElementById('manyYAxisChart'));
// 颜色数组 为了让线条颜色与折线颜色一致 从echarts的默认主题里copy下来的
let color = [
"#5470c6",
"#91cc75",
"#fac858",
"#ee6666",
"#73c0de",
"#3ba272",
"#fc8452",
"#9a60b4",
"#ea7ccc",
]
//构建option
let allYAxis = []; //所有的Y轴
let allSeries = []; //所有的series
let offset = [0,]; //Y轴的偏移量数组,第一个Y轴不需要偏移
let legendData = []; //所有的系列名称
for (let i=0; i<allData.length; i++){
offset.push( (i+1) * 40 );
let axisName = 'y'+ (i+1);
let singleYAxis = {
id: axisName,
name: axisName,
type: 'value',
show: true,
position:'left',
axisLine: {onZero: false, show: true, lineStyle: {color: color[i]}},
splitLine: {show: i === 0},
// axisTick: {show: true,}, //坐标轴刻度相关设置
alignTicks: true, //在多个y轴为数值轴的时候,可以开启该配置项自动对齐刻度。只对'value'和'log'类型的轴有效
offset: offset[i],
}
allYAxis.push(singleYAxis);
let seriesName = 'series' + (i + 1);
let singleSeries = {
id: seriesName,
name: seriesName,
type: 'line',
data: allData[i],
yAxisIndex: i,
}
allSeries.push(singleSeries);
legendData.push(seriesName);
}
// 使图表整体向右偏移,留出Y轴的位置
let chartOffset = 40 * allData.length + 40;
myChart.setOption({
title: {text: '多Y轴折线图', left: 'center',},
tooltip: {show: true, trigger: 'axis', axisPointer: {type: 'cross',}},
legend: { data: legendData, top: '5%', right: 100},
// grid: { containLabel: true, }, //这常用于『防止标签溢出』的场景,标签溢出指的是,标签长度动态变化时,可能会溢出容器或者覆盖其他组件
// grid.left grid 组件离容器左侧的距离。
grid: { left: chartOffset, },
xAxis: {type: 'value', axisLine: {onZero: false}},
yAxis: allYAxis,
series: allSeries,
});
// 让图表自适应
window.addEventListener('resize', () => {
if (myChart) {
myChart.resize();
}
})
}
}
}
</script>
<style scoped>
</style>
Vue Echarts 绘制多Y轴折线图
最新推荐文章于 2024-06-04 18:28:45 发布