const rootData = '你的参数'
var sort = [false, false];
setTimeout(() => {
initChart(rootData)
});
function initChart(res) {
// 根据排序条件处理数据
if (sort[0]) {
res = ([].concat(rootData)).sort((a, b) => {
return a.indicatorTree - b.indicatorTree
})
} else if (sort[1]) {
res = ([].concat(rootData)).sort((a, b) => {
return a.indicatorOne - b.indicatorOne
})
}else if(sort[2]){
res = ([].concat(rootData)).sort((a, b) => {
return a.indicatorTwo - b.indicatorTwo
})
}
let data = [
{
name: '总和',
data: res.map(v => v.indicatorTree),
},
{
name: '网费',
data: res.map(v => v.indicatorOne),
},
{
name: '商品',
data: res.map(v => v.indicatorTwo),
}
]
let axis = res.map(v => v.name)
let colors = ['#ff3824','#3c54ff', '#23af41']
let richStyle = {
a: {
color: "#fff",
fontSize: 9,
fontWeight:600,
verticalAlign: 'middle'
}
}
let legendSelected = {}
let legendData = []
data.forEach((v, i) => {
legendSelected[v.name] = true // 默认选中所有图例
legendData.push({
name: data[i].name,
selected: true,
textStyle: {
rich: {
a: {
color: sort[i] ? "#00a0f8" : '#3d3d3d',
fontSize: 12,
fontWeight:600,
verticalAlign: 'middle'
}
}
}
})
})
let option = {
backgroundColor: '#F1F1F4',
color: colors,
legend: {
textStyle: {
color: '#3d3d3d',
fontSize: 9,
fontWeight:600
},
itemGap: 50,
itemWidth: 15,
itemHeight: 18,
icon: 'rect',
top: '5%',
left: 'center',
selected: legendSelected,
data: legendData,
formatter: name => `${name} {a|⇅}`
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
top: '15%',
left: '20%',
right: '0%',
bottom: '10%',
width: '80%',
height: '80%'
},
xAxis: {
axisLine: {
lineStyle: {
color: '#d2d2d2'
}
},
splitLine: {
show: true,
lineStyle: {
color: '#cdcdcd'
}
},
axisLabel: {
textStyle: {
color: '#3d3d3d',
fontSize: 9,
fontWeight:600
},
color: "#e2e2e2"
},
},
yAxis: {
axisTick: {
alignWithLabel: true,
},
axisLine: {
lineStyle: {
color: '#d2d2d2'
}
},
axisLine: {
lineStyle: {
color: '#3d3d3d'
}
},
axisLabel: {
textStyle: {
color: '#00a0f8',
fontSize: 9,
fontWeight:600
},
},
data: axis
},
series: [
{
name: data[0].name,
type: 'bar',
barGap: '-100%',
barWidth: 0,
data: data[0].data,
label: {
normal: {
show: true,
position: 'right',
textStyle: { color: '#ff3824' ,fontSize: 9,fontWeight:600}
}
},
},
{
name: data[1].name,
type: 'bar',
stack: 'one',
barWidth: 0,
data: data[1].data,
label: {
show: true,
textStyle: { //数值样式
color: '#fff',
fontSize: 9,
fontWeight:600
}
},
},
{
name: data[2].name,
type: 'bar',
stack: 'one',
barWidth: 0,
data: data[2].data,
label: {
show: true,
textStyle: { //数值样式
color: '#fff',
fontSize: 9,
fontWeight:600
}
},
},
]
};
let myChart = echarts.init(document.getElementById('myChart'));
myChart.setOption(option);
myChart.off('legendselectchanged') // 取消事件,避免事件绑定重复导致多次触发
myChart.on('legendselectchanged', e => {
let index = data.findIndex(v => v.name === e.name)
let flag = sort[index]
sort = sort.map(v => false) // 全部重置为false,保证同时只能根据一个字段排序
sort[index] = !flag
initChart(rootData)
})
}
echarts点击按钮排序
最新推荐文章于 2024-04-15 16:42:15 发布