如何不借助highcharts-react-official库用React Highcharts实现堆叠环形图
用React Highcharts实现堆叠环形图(替代highcharts-react-official)
1. 替换依赖库
先卸载禁用的highcharts-react-official,安装官方维护的react-highcharts:
npm uninstall highcharts-react-official npm install react-highcharts highcharts
2. 堆叠环形图核心配置
要实现堆叠环形,关键配置点:
- 开启饼图堆叠:在
plotOptions.pie里设置stacking: 'normal' - 设置环形内半径:
innerSize: '60%'(可根据需求调整) - 多系列数据:每个堆叠层对应一个
series,每个系列的type为pie,并指定stack属性(同一堆叠组用相同值) - 中心平均值:通过Highcharts的
renderer在图表中心绘制文本,提前计算各系列数据的平均值
3. 完整React组件示例
import React, { useEffect, useRef } from 'react'; import ReactHighcharts from 'react-highcharts'; const StackedDonutChart = () => { const chartRef = useRef(null); // 模拟数据,可替换为实际业务数据 const seriesData = [ { name: '层1', data: [20, 30, 25], stack: 'donut', color: '#007bff' }, { name: '层2', data: [15, 25, 20], stack: 'donut', color: '#28a745' }, { name: '层3', data: [10, 15, 10], stack: 'donut', color: '#ffc107' } ]; // 计算所有数据的平均值并转成百分比 const calculateAvg = () => { let total = 0; let count = 0; seriesData.forEach(series => { series.data.forEach(val => { total += val; count++; }); }); return Math.round((total / count)) + '%'; // 示例计算后为84% }; const options = { chart: { type: 'pie', height: 300 }, title: { text: '' }, tooltip: { pointFormat: '{series.name}: <b>{point.y}</b>' }, plotOptions: { pie: { stacking: 'normal', innerSize: '60%', dataLabels: { enabled: false // 禁用默认数据标签,按需开启 } } }, series: seriesData }; useEffect(() => { if (chartRef.current) { const chart = chartRef.current.getChart(); // 在中心添加平均值文本 const centerX = chart.plotLeft + chart.plotWidth / 2; const centerY = chart.plotTop + chart.plotHeight / 2; chart.renderer.text(calculateAvg(), centerX, centerY) .attr({ align: 'center', verticalAlign: 'middle', fontSize: '24px', fontWeight: 'bold' }) .add(); } }, []); return <ReactHighcharts ref={chartRef} config={options} />; }; export default StackedDonutChart;
关键说明
- 堆叠逻辑:所有
series的stack属性设为相同值,Highcharts会自动将它们堆叠成环形 - 中心文本:通过
renderer.text()手动绘制,确保显示在环形中心 - 样式调整:可通过修改
innerSize、颜色、字体大小等参数匹配附图样式
内容的提问来源于stack exchange,提问作者pranathi tammina
相关产品推荐
相关产品推荐

