背景:
echarts饼图中心位置需要显示总数,在legend发生改变时,实时计算已选lengend的总数。
展示label
show: true
foramtter: 展示的格式
rich: 定义label的样式
series: [
{
label: {
show: true,
position: 'center',
formatter: `{total|30}\r\n{text|总数}`,
rich: {
total: {
fontSize: 32,
lineHeight: 40,
color: '#8b8c8f',
fontWeight: 'bold'
},
text: {
fontSize: 16,
lineHeight: 22,
color: '#8b8c8f',
fontWeight: 'bold',
padding: [7, 0, 0, 0]
}
}
}
}
]
注册legendselectchanged事件
echartsInstance.on('legendselectchanged', param => {
if (param) {
let { selected } = param;
let data; // 原始数据, series[0].data
// 汇总所有已选的legend数据
let total = data.reduce((count, next) => {
count += selected[next.name] ? next.value : 0;
return count;
}, 0);
// 重新刷新echarts视图
e.setOption({
series: [
{
label: {
formatter: `{total|${total}}\n\r{text|总数}}`,
},
},
],
});
}
});
echarts的setOption居然可以只更新某个属性,不需要重新初始化。