想在echarts中實現excel 中的百分比堆積圖,無奈在官網沒有找到相似demo,花了1小時最終完美實現。
2個柱子在總數不同的時候,只要百分比對,全部有柱子同高。
思路以下:
1.y軸設置爲0-100%;
2.兩個堆積的柱狀圖先計算出其佔的百分比,用於渲染柱子;
3.用formatter 在柱子上顯示真實的數值(非百分比);
4.用formatter 在柱子上顯示自定義的tooltip;react
import React, {Component} from 'react'; import ReactEcharts from 'echarts-for-react'; import {formatterToolTip} from './../../../../utils/util'; class Test extends Component { state = { dataArr: [80, 100, 120, 140, 160, 130, 80], dataArrPercent: [40, 50, 60, 70, 80, 65, 40], dataArr2: [120, 100, 80, 60, 40, 70, 120], dataArrPercent2: [60, 50, 40, 30, 20, 35, 60], } render() { const {dataArr, dataArrPercent, dataArr2, dataArrPercent2} = this.state; const option = { title: { text: '行爲分析', show: true, textStyle: { color: '#333333', fontSize: 16, }, x: 'center' }, tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: (params, ticket, callback) => { let index = params[0]['dataIndex']; // 不能傳更多參數,先把參數params增長一個自定義的key:currentData表示真實數據 if (params[0]) { params[0]['currentData'] = dataArr[index]; } if (params[1]) { params[1]['currentData'] = dataArr2[index]; } return formatterToolTip(params, ticket, callback); } }, legend: { data: ['AA', 'BB'], left: 'center', bottom: 10 }, xAxis: { type: 'category', data: ["20190806","20190807","20190808","20190809","20190810","20190811","20190812"] }, yAxis: { type: 'value', min: 0, max: 100, axisLabel: { show: true, interval: 'auto', formatter: '{value} %' }, show: true }, series: [ { name: 'AA', type: 'bar', stack: '總量', label: { normal: { show: true, position: 'inside', formatter: (v) => { return dataArr[v.dataIndex]; } }, }, itemStyle: { color: '#5b9bd5' }, data: dataArrPercent }, { name: 'BB', type: 'bar', stack: '總量', label: { normal: { show: true, position: 'inside', formatter: (v) => { return dataArr2[v.dataIndex]; } }, }, itemStyle: { color: '#ed7d31' }, data: dataArrPercent2 }, ] }; return ( <div> <ReactEcharts option={option} style={{height: '300px', width: '100%'}} theme='theme' ></ReactEcharts> </div> ); } } export default Test;
// 格式化ToolTip展現文案 export function formatterToolTip(params, ticket, callback) { let tipString = `${params[0].axisValue}<br/>`;// 顯示提示文字模板 for (let i = 0, length = params.length; i < length; i++) { tipString += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background:${params[i].color}"></span>`; tipString += `${params[i].seriesName}: ${params[i].currentData}(${params[i].value}%)<br/>`; } return tipString; }