| 1 | import * as echarts from 'echarts'; |
| 2 | import { CallbackDataParams } from 'echarts/types/src/util/types'; |
| 3 | |
| 4 | type EChartsOption = echarts.EChartsOption; |
| 5 | |
| 6 | const initWeepPie = ( |
| 7 | chartDom: HTMLDivElement, |
| 8 | data: { |
| 9 | value: number; |
| 10 | name: string; |
| 11 | }[], |
| 12 | ) => { |
| 13 | if (!chartDom) return; |
| 14 | const myChart = echarts.init(chartDom); |
| 15 | |
| 16 | const option: EChartsOption = { |
| 17 | tooltip: { |
| 18 | trigger: 'item', |
| 19 | formatter: (params: echarts.TooltipComponentFormatterCallbackParams) => { |
| 20 | params = params as CallbackDataParams; |
| 21 | const total = data.reduce((sum, item) => sum + item.value, 0); |
| 22 | const percent = (((params.value as number) / total) * 100).toFixed(2); // 计算百分比并保留两位小数 |
| 23 | return `${params.name}: ${params.value} (${percent}%)`; // 格式化显示文本 |
| 24 | }, |
| 25 | }, |
| 26 | series: [ |
| 27 | { |
| 28 | type: 'pie', |
| 29 | radius: '60%', |
| 30 | label: { |
| 31 | formatter: (params: any) => { |
| 32 | const total = data.reduce((sum, item) => sum + item.value, 0); |
| 33 | const percent = ((params.value / total) * 100).toFixed(0); // 百分比 |
| 34 | return `${params.name} ${params.value}(${percent}%) `; // 自定义显示名称、数值和百分比 |
| 35 | }, |
| 36 | }, |
| 37 | data, |
| 38 | }, |
| 39 | ], |
| 40 | }; |
| 41 | |
| 42 | if (option) myChart.setOption(option); |
| 43 | }; |
| 44 | |
| 45 | export default initWeepPie; |
| 46 |