You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不借助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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 07:18:32