There are already answered questions on how to add a 'total' label on top of a stacked bar chart on echarts (e.g. this one)
However, I also want this total to recalculate when series are selected/deselected using the legend (including if I deselect the final series to which the label is attached in the example below). Is this possible?
Example code from the other question:
//example data
this.mySeries = [{
name: 'Dataset 1',
type: 'bar',
stack: 'Stack 1',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: 'Dataset 2',
type: 'bar',
stack: 'Stack 1',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: 'Dataset 3',
type: 'bar',
stack: 'Stack 1',
data: [820, 932, 901, 934, 1290, 1330, 1320],
}
];
//function for formatter
genFormatter = (series) => {
return (param) => {
console.log(param);
let sum = 0;
series.forEach(item => {
sum += item.data[param.dataIndex];
});
return sum
}
};
//inside your chart options place this
series: series.map((item, index) => Object.assign(item, {
type: 'bar',
stack: true,
label: {
show: index === series.length - 1,
formatter: genFormatter(series),
fontSize: 20,
color: 'black',
position: 'top'
},
})),