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

React Charts:值全为零时仍显示均分彩色饼图及零值提示

需求可实现,解决方案如下

核心思路

  • 当两个数值均为零时,将饼图数据临时设为[1, 1],强制饼图均分显示并保留原有配色
  • 通过自定义Tooltip回调,让鼠标悬浮时显示真实的零值,而非临时替换的1
  • 非全零场景下正常使用原始数据,不影响原有逻辑

修改后的完整代码

import { Pie } from "react-chartjs-2";
import { ArcElement, Chart as ChartJS, Legend, Tooltip } from "chart.js";
ChartJS.register(ArcElement, Tooltip, Legend);

const LimitChart = ({ data, sectorNameBySectorCode }: { data: ISectorLimit, sectorNameBySectorCode: string }) => {
  const { t } = useTranslation();

  // 判断是否两个值都为零
  const bothZero = !(data.remainingLimit || data.usedLimit);

  const chartData = React.useMemo(() => {
    // 处理数据:全零时用[1,1]强制均分,否则用实际值(兜底为0)
    const chartValues = bothZero 
      ? [1, 1] 
      : [data.remainingLimit || 0, data.usedLimit || 0];

    return {
      labels: [t("label.remainingLimit"), t("label.usedLimit")],
      datasets: [
        {
          data: chartValues,
          backgroundColor: [
            chartColorLookup[sectorNameBySectorCode as SectorNames].secondary,
            chartColorLookup[sectorNameBySectorCode as SectorNames].primary
          ],
          borderWidth: 2,
        },
      ],
    };
  }, [data, sectorNameBySectorCode, t]);

  // 自定义Tooltip配置,显示真实值
  const chartOptions = React.useMemo(() => ({
    tooltip: {
      callbacks: {
        label: function(context) {
          const label = context.label || '';
          // 全零时显示0,否则显示原始数据值
          const value = bothZero ? 0 : context.parsed;
          return `${label}: ${value}`;
        }
      }
    }
  }), [bothZero]);

  return (
    <Pie data={chartData} options={chartOptions} width={200} height={200}/>
  );
};

关键细节说明

  • 数据替换逻辑:全零时用[1,1]是因为Chart.js对全零数据会隐藏饼图,用相等的非零值可以强制生成两个均分的扇区,同时不破坏配色比例
  • Tooltip自定义:通过tooltip.callbacks.label回调,根据bothZero状态决定显示真实的零值,保证悬浮提示的准确性
  • 依赖项优化:useMemo的依赖数组补充了t和sectorNameBySectorCode,避免因依赖缺失导致的不必要重渲染或数据错误

内容的提问来源于stack exchange,提问作者emre-ozgun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:45:36