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); })
效果:
原文:https://www.cnblogs.com/huaxiaguyuan/p/11097474.html