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

如何将Object.values统计值除以total计算百分比用于图表数据集

解决方案

你只需要调整统计值转百分比的计算逻辑,再可选配置饼图提示框的后缀即可,修改后完整代码如下:

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

ChartJS.register(ArcElement, Tooltip, Legend);

export default function App() {
  const data = [
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: false,
        type1: true,
        selectedItem: "car"
      },
      displayName: "Person1"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "bikes"
      },
      displayName: "Person2"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "car"
      },
      displayName: "Person3"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "motor"
      },
      displayName: "Person4"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "motor"
      },
      displayName: "Person5"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "truck"
      },
      displayName: "Person6"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "bikes"
      },
      displayName: "Person7"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "truck"
      },
      displayName: "Person8"
    }
  ];

  const total = 12;

  let res = [...data].reduce(
    (a, c) => (
      (a[c.items.selectedItem] = (a[c.items.selectedItem] || 0) + 1), a
    ),
    {}
  );

  // 核心修改:将原始统计值转换为百分比
  const rounded = Object.entries(res).reduce((acc, [key, value]) => {
    const percentValue = Number(((value / total) * 100).toFixed(2));
    return { ...acc, [key]: percentValue };
  }, {});

  return (
    <div className="App">
      <Pie
        data={{
          labels: Object.keys(rounded),
          datasets: [
            {
              data: Object.values(rounded),
              backgroundColor: ["red", "yellow", "green", "blue", "pink"],
              borderColor: ["rgba(255, 99, 132, 1)"],
              borderWidth: 1
            }
          ]
        }}
        height={400}
        width={600}
        options={{
          maintainAspectRatio: false,
          title: {
            display: true,
            text: "Selected",
            fontSize: 20
          },
          legend: {
            labels: {
              fontSize: 25
            }
          },
          // 可选配置:鼠标悬浮提示框显示%后缀
          plugins: {
            tooltip: {
              callbacks: {
                label: (context) => `${context.label}: ${context.parsed}%`
              }
            }
          }
        }}
      />
    </div>
  );
}

核心修改说明

  • 统计值转换逻辑:用(单个分类数量 / 预设总量total) * 100计算得到百分比数值,保留2位小数后转为数字类型,避免图表组件解析字符串异常
  • 提示框配置:新增tooltip回调,在悬浮提示时自动拼接%后缀,符合百分比展示习惯

内容的提问来源于stack exchange,提问作者JS3

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:24:03