Echarts本身沒提供現成的解決方案。
option = {
title: {
text: '分類銷量'
},
legend: {
y: "bottom",
data: ['百貨', '電子', '服裝']
},
xAxis: [
{
type: "category",
data: [
20190612,
20190613,
20190614,
20190615
]
}
],
yAxis: [
{
type: "value"
}
],
series: [
{
name: "百貨",
type: "bar",
stack: "1",
data: [
10,
14,
17,
8
],
},
{
name: "電子",
type: "bar",
stack: "1",
data: [
16,
12,
9,
22
]
},
{
name: "服裝",
type: "bar",
stack: "1",
data: [
18,
8,
13,
20
],
label: {
show: true,
position: 'top',
color: 'black',
formatter: function (params){
return params.value
}
}
}
]
}
思路: 將最后一類的label用formatter函數處理為總和。
js處理將fun綁定到最后一個series上
var series = option["series"];
var fun = function (params) {
var datavalue = 0;
for (var i = 0; i < series.length; i++) {
datavalue += series[i].data[params.dataIndex]
}
return datavalue;
}
series[series.length - 1]["label"]["formatter"] = fun;
一般的方案到這里就結束了,忽略了ECharts的圖例選擇取消功能,如果user將最后一個圖例做取消顯示時就會存在問題,
所以還需要進一步處理
myChart.on("legendselectchanged", function (obj) {
var b = obj.selected, d = [];
for (var key in b) {
if (b[key]) {
for (var i = 0, l = series.length; i < l; i++) {
var changename = series[i]["name"];
if (changename == key) {
d.push(i);
}
}
}
}
var fun = function (params) {
var datavalue = 0;
for (var i = 0; i < d.length; i++) {
for (var j = 0; j < series.length; j++) {
if (d[i] == j) {
datavalue += series[j].data[params.dataIndex]
}
}
}
return datavalue
}
for (var i = 0; i < series.length; i++) {
series[i]["label"]["show"] = false;
}
for (var i = series.length - 1; i >= 0; i--) {
var name = series[i]["name"];
if (obj["selected"][name]) {
series[i]["label"]["formatter"] = fun1
series[i]["label"]["show"] = true
break;
}
}
myChart.setOption(option);
})
效果:

