Newer
Older
Nathan Marye
a validé
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"use client";
import React, {useEffect, useRef} from "react";
import * as d3 from "d3";
const defaultColorScheme = [
"#1e64af", "#419bd2", "#69beeb", "#d7b428", "#e19196",
"#a5236e", "#eb1e4b", "#f06937", "#f5dc50", "#2d969b",
"#335c6c", "#ff7d2d", "#fac846", "#a0c382", "#5f9b8c",
"#325a69", "#fff5af", "#e1a03c", "#a0282d", "#550a0f"
];
/**
* @param {object} props
* @param {[{id: string, count: number}]} props.data
*/
export default function Donut({data}) {
const ref = useRef();
const width = 250;
const height = 250;
const padding = 20;
const thicknessOnMouseOver = 10;
const radius = Math.min(width, height) / 2 - padding;
const deathAngle = 0.2;
useEffect(() => {
const rawPieData = d3.pie().value((x) => x.count)(data);
let pieData = [];
const aggregate = {
data: {
id: "aggregate",
count: 0
},
index: rawPieData.length,
value: 0,
padAngle: 0,
startAngle: 0,
endAngle: Math.PI * 2
};
let lastEndAngle = 0;
for (const d of rawPieData) {
if (d.endAngle > lastEndAngle) {
lastEndAngle = d.endAngle;
}
// if d angle is less than deathAngle, we don't show it in final donut
if (d.endAngle - d.startAngle < deathAngle) {
aggregate.startAngle = lastEndAngle;
aggregate.endAngle -= d.endAngle - d.startAngle;
aggregate.value += d.value;
aggregate.data.count += d.data.count;
} else {
pieData.push(d);
}
}
pieData.push(aggregate);
const arc = d3
.arc()
.innerRadius(radius * 0.6)
.outerRadius(radius)
d3.select(ref.current)
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", `translate(${width/2}, ${height/2})`)
.selectAll("path")
.data(pieData)
.enter()
.append("path")
.attr("d", arc)
.attr("fill", (x, i) => x.data.id === "aggregate" ? "#dddddd" : defaultColorScheme[i % data.length])
.on("mouseover", function() {
d3.select(this)
.transition()
.duration(200)
.attr("stroke", this.attributes.fill.nodeValue)
.attr("stroke-width", thicknessOnMouseOver);
this.parentNode.appendChild(this);
})
.on("mouseout", function() {
d3.select(this)
.transition()
.attr("stroke", "none")
.attr("stroke-width", 0);
});
}, [data]);
return (
<svg ref={ref}></svg>
);
}