echarts柱状图两列单位不同
代码
<div id="echarts" :style="{width:'700px',height:'600px',margin:'0 auto'}" />
导入echarts
import echarts from 'echarts'
模拟后端传过来的数据
data() {
return {
resData: {
data: [{ name: '数据1', value: 14 }, { name: '数据2', value: 1 }, { name: '数据3', value: 4 }, { name: '数据4', value: 14 }, { name: '数据5', value: 14 }],
size: [{ name: '尺寸1', value: 14 }, { name: '尺寸2', value: 1 }, { name: '尺寸3', value: 4 }, { name: '尺寸4', value: 14 }, { name: '尺寸5', value: 14 }]
}
}
}
mounted() {
// 根据窗口大小调整echarts图表
window.onresize = () => {
// 基于准备好的dom,初始化echarts实例
const myChart = echarts.init(document.getElementById('echarts'))
myChart.resize()
}
this.getChart()
},
beforeDestroy() {
window.onresize = null
},
methods: {
getChart() {
const myChart = echarts.init(document.getElementById('echarts'))
const firstData = [] // 第一列数据
const secondSize = [] // 第二列数据
const namelist = []
// 整合图表所需的数据
this.resData.data.forEach(e => {
namelist.push(e.name)
firstData.push({ type: 'bar', name: e.name, yAxisIndex: 0, stack: 'data', data: [e.value, 0] })
})
this.resData.size.forEach(el => {
namelist.push(el.name)
secondSize.push({ type: 'bar', name: el.name, yAxisIndex: 1, stack: 'data', data: [0, el.value] })
})
const option = {
tooltip: {
trigger: 'item',
axisPointer: {
type: 'shadow'
},
formatter: function(params) {
var tooltip = params.seriesName + '<br/>' + params.name + ' : ' + params.value
// 自定义提示的单位
if (params.name === '数据') {
return tooltip + '个'
} else {
return tooltip + '厘米'
}
}
},
legend: {
type: 'scroll', // 设置滚动翻页
data: namelist
},
color: ['#2f4554', '#308e92', '#b1cfa5', '#f5d69f', '#c23531', '#ef5055', '#bda29a', '#5470c6', '#91cc75',
'#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'], // 自定义颜色
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
data: ['数据', '尺寸']
},
yAxis: [{
type: 'value',
name: '数据',
position: 'left',
axisLine: {
show: false
},
axisLabel: {
show: true,
showMinLabel: true,
showMaxLabel: true,
formatter: '{value}'
},
axisTick: {
show: false
}
}, {
type: 'value',
name: '尺寸',
position: 'right',
axisLine: {
show: false
},
axisLabel: {
show: true,
showMinLabel: true,
showMaxLabel: true,
formatter: '{value}'
},
axisTick: {
show: false
}
}],
series: [...firstData, ...secondSize]
}
myChart.setOption(option)
}
}
}