echarts堆疊柱狀圖在最上面的柱子顯示總和

需求

  • 柱子需設置barMinHeight
  • 在堆疊柱狀圖的最上面顯示當前堆疊的總和

直接上程式碼吧

需要注意:設置barMinHeight時為了讓0不顯示,只能將0設置為null;
設置為null的柱子label是不顯示的。當null在最上面時label就沒得了
const series = [{ name: '張三', type: 'bar', stack: '總量', barWidth: 50, color: '#2457b3', barMinHeight: 5, data: [0, 1700, 1400, 1200, 300, 1] }, { name: '李四', type: 'bar', stack: '總量', barWidth: 50, color: '#2b91c3', barMinHeight: 5, data: [2900, 1200, 300, 200, 900, null] }, { name: '王五', type: 'bar', stack: '總量', barWidth: 50, color: '#2b9FF3', barMinHeight: 5, label: { color: '#333', position: 'top' }, data: [800, 900, null, 400, 80, 60] }] const option = { title: { text: '深圳月最低生活費組成(單位:元)', subtext: 'From ExcelHome', sublink: '//e.weibo.com/1341556070/AjQH99che' }, tooltip: { trigger: 'axis', axisPointer: { // 坐標軸指示器,坐標軸觸發有效 type: 'shadow' // 默認為直線,可選為:'line' | 'shadow' }, }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'category', splitLine: { show: false }, data: ['總費用', '房租', '水電費', '交通費', '伙食費', '日用品數'] }, yAxis: { type: 'value' }, }; let sums = []; let stacks = ['張三', '李四', '王五']; let labelInfo = { show: true, color: '#333', position: 'top' } series.forEach((item, sIdx) => { item.data.forEach((val, idx) => { sums[idx] = (sums[idx] || 0) + (val || 0); }) labelInfo.series = JSON.parse(JSON.stringify(series)); labelInfo.formatter = function(param) { // 此處可以寫個函數,param.seriesIndex + 1(2,3,4,5等等) if (labelInfo.series && ((labelInfo.series[param.seriesIndex + 1] && labelInfo.series[param.seriesIndex + 1].data[param.dataIndex]) || (labelInfo.series[param.seriesIndex + 2] && labelInfo.series[param.seriesIndex + 2].data[param.dataIndex]) ) ) { return ''; } else { return sums[param.dataIndex] } } item.label = labelInfo; }) option.series = series; console.log(sums, option); var chartDom = document.getElementById('chart'); var myChart = echarts.init(chartDom); option && myChart.setOption(option);

Tags: