File size: 2,054 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"use client"

import { Chart, useChart } from "@chakra-ui/charts"
import { Cell, Pie, PieChart, Tooltip } from "recharts"

interface DataItem {
  name: string
  value: number
  color: string
}

const rawData: DataItem[] = [
  { name: "windows", value: 400, color: "blue.solid" },
  { name: "mac", value: 300, color: "orange.solid" },
  { name: "linux", value: 150, color: "pink.solid" },
  { name: "chrome", value: 80, color: "purple.solid" },
  { name: "firefox", value: 60, color: "red.solid" },
  { name: "safari", value: 40, color: "yellow.solid" },
  { name: "edge", value: 30, color: "cyan.solid" },
  { name: "opera", value: 20, color: "teal.solid" },
]

const threshold = 100

// Group items with value < 100 into "Other"
const data = rawData.reduce<DataItem[]>((acc, item) => {
  if (item.value >= threshold) {
    acc.push(item)
  } else {
    const otherIndex = acc.findIndex((i) => i.name === "Other")
    if (otherIndex === -1) {
      acc.push({ name: "Other", value: item.value, color: "gray.emphasized" })
    } else {
      acc[otherIndex].value += item.value
    }
  }
  return acc
}, [])

export const DonutChartWithOtherLabel = () => {
  const chart = useChart({ data: data })

  const label = (entry: DataItem) => {
    const percent = chart.getValuePercent("value", entry.value)
    return `${entry.name} (${percent.toFixed(1)}%)`
  }

  return (
    <Chart.Root aspectRatio="square" maxW="sm" chart={chart} mx="auto">
      <PieChart>
        <Tooltip
          cursor={false}
          animationDuration={100}
          content={<Chart.Tooltip hideLabel />}
        />
        <Pie
          innerRadius={60}
          outerRadius={100}
          isAnimationActive={false}
          data={chart.data}
          dataKey={chart.key("value")}
          nameKey={chart.key("name")}
          label={label}
          labelLine={{ strokeWidth: 1 }}
        >
          {chart.data.map((item) => (
            <Cell key={item.name} fill={chart.color(item.color)} />
          ))}
        </Pie>
      </PieChart>
    </Chart.Root>
  )
}