-
Notifications
You must be signed in to change notification settings - Fork 0
/
d3pie.js
417 lines (357 loc) · 15.3 KB
/
d3pie.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*!
* rspamd-D3Pie 1.1.0 (https://github.com/moisseev/rspamd-D3Pie)
* Copyright (c) 2022, Alexander Moisseev, BSD 2-Clause
*/
/* exported D3Pie */
/* eslint-disable-next-line max-statements, no-implicit-globals */
function D3Pie (id, options) {
"use strict";
const opts = $.extend(true, {
canvasPadding: 5,
cornerRadius: 3,
duration: 1250,
gradient: {
enabled: true,
percentage: 100
},
labels: {
inner: {
hideWhenLessThanPercentage: 4,
offset: 0.15
},
outer: {
collideHeight: 13,
format: "label",
pieDistance: 30
}
},
padAngle: 0.01,
pieCenterOffset: {
x: 0,
y: 0
},
size: {
canvasHeight: 400,
canvasWidth: 600,
pieInnerRadius: "20%",
pieOuterRadius: "85%"
},
title: "",
total: {
enabled: false
}
}, options);
this.destroy = function () {
d3.selectAll("#" + id + " svg, #" + id + "-tooltip").remove();
};
this.destroy();
const svg = d3.select("#" + id).append("svg")
.attr("class", "d3pie")
.attr("width", opts.size.canvasWidth)
.attr("height", opts.size.canvasHeight);
let titleHeight = 0;
if (opts.title !== "") {
const title = svg.append("svg:text")
.attr("class", "chart-title")
.attr("x", (opts.size.canvasWidth / 2));
title.append("tspan")
.text(opts.title + " ");
titleHeight = title.node().getBBox().height;
title.attr("y", titleHeight + opts.canvasPadding);
}
const g = svg.append("g")
.attr("transform", "translate(" + ((opts.size.canvasWidth / 2) + opts.pieCenterOffset.x) + "," +
((opts.size.canvasHeight / 2) + (titleHeight / 2) + opts.pieCenterOffset.y + ")"));
const currentData = {};
const outerLabel = {};
const {outerRadius, innerRadius} = (function () {
function pieRadius (r, whole) {
if (!(/%/u).test(r)) return parseInt(r, 10);
const decimal = Math.max(0, Math.min(99, parseInt(r.replace(/[\D]/u, ""), 10))) / 100;
return Math.floor(whole * decimal);
}
const width = opts.size.canvasWidth - (2 * opts.canvasPadding);
const height = opts.size.canvasHeight - (2 * opts.canvasPadding) - titleHeight;
let overallRadius = Math.min(width, height) / 2;
if (opts.labels.outer.format !== "none") {
const pieDistance = parseInt(opts.labels.outer.pieDistance, 10);
if (overallRadius > pieDistance) overallRadius -= pieDistance;
}
const oR = pieRadius(opts.size.pieOuterRadius, overallRadius);
const iR = pieRadius(opts.size.pieInnerRadius, oR);
return {outerRadius: oR, innerRadius: iR};
}());
const labelRadius = outerRadius + opts.labels.outer.pieDistance;
const lineGenerator = d3.line()
.curve(d3.curveCatmullRomOpen);
const tooltip = d3.select("body").append("div")
.attr("id", id + "-tooltip")
.attr("class", "d3pie-tooltip");
const tooltipText = tooltip
.append("span")
.attr("id", id + "-tooltip-text");
function attachListeners (selection) {
selection
.on("mouseover", function (_, d) {
const tot = tooltip.datum().total;
const percentage = (tot) ? Math.round(100 * d.data.value / tot) : NaN;
if (d.data.value) {
tooltip
.transition().duration(300)
.style("opacity", 1);
tooltipText
.text(d.data.label + ((tot) ? ": " + d.data.value + " (" + percentage + "%)" : ""));
} else {
tooltip.transition().duration(300).style("opacity", 0);
}
// eslint-disable-next-line no-invalid-this
tooltip.each(function (datum) { datum.height = this.getBoundingClientRect().height; });
})
.on("mouseout", function () {
tooltip.transition().duration(300).style("opacity", 0);
})
.on("mousemove", (event) => {
const {pageX, pageY} = event;
tooltip
.style("left", (pageX) + "px")
.style("top", function (d) { return (pageY - d.height - 2) + "px"; });
});
}
const totalG = g.append("g");
attachListeners(totalG);
totalG.append("circle")
.attr("r", innerRadius)
.style("opacity", 0);
if (opts.total.enabled) {
const totalText = totalG.append("text")
.attr("class", "total-text");
totalText.append("tspan")
.attr("class", "total-value")
.style("font-size", (0.6 * innerRadius) + "px");
totalText.append("tspan")
.attr("x", "0")
.attr("dy", 0.5 * innerRadius)
.text((typeof opts.total.label !== "undefined") ? opts.total.label : "Total");
}
const defs = svg.append("defs");
this.data = function (arg) {
let data = $.extend(true, [], arg);
const nodes = [];
const total = data.reduce(function (a, b) {
return a + (b.value || 0);
}, 0);
tooltip.datum({total});
totalG.datum({
data: {
label: (typeof opts.total.label !== "undefined") ? opts.total.label : "Total",
value: total
}
});
if (opts.total.enabled) totalG.select(".total-value").text(d3.format(".3~s")(total));
// Add placeholder path for empty pie chart
data.unshift({
label: "undefined",
color: opts.gradient.enabled ? "steelblue" : "#ecf1f5",
value: (total === 0) ? 1 : 0
});
const colorScale = d3.scaleOrdinal(d3.schemeSet1);
function pathColor (d, i) {
return (typeof d !== "undefined" &&
typeof d.color !== "undefined")
? d.color
: colorScale(i);
}
function midpoint (args, innerR, outerR = innerR) {
return d3.arc().innerRadius(innerR).outerRadius(outerR).centroid(args);
}
function interpolate (d) { return d3.interpolate(currentData[d.data.label], d); }
function arcTweenSlice (d) {
return function (t) {
return d3.arc().padAngle(opts.padAngle).cornerRadius(opts.cornerRadius)
.innerRadius(innerRadius).outerRadius(outerRadius)(interpolate(d)(t));
};
}
function arcTweenInnerlabel (d) {
return function (t) {
return "translate(" + midpoint(
interpolate(d)(t),
innerRadius * (1 - opts.labels.inner.offset),
outerRadius * (1 + opts.labels.inner.offset)
) + ")";
};
}
function limit (y) {
// Avoid 0 and pi positions to prevent changing half-plane
const boundary = labelRadius - 0.1;
return Math.max(-boundary, Math.min(boundary, y));
}
function arcTweenOuterlabel (d, i) {
function newAngle () {
// Node Y may be slightly outside of the circle as the bounding force is not a hard limit.
const y = limit(nodes[i].y);
// Calculate the actual X-position with an equation of a circle centered at the origin (0, 0).
let ax = Math.sqrt(Math.pow((labelRadius), 2) - Math.pow(y, 2));
if ((d.endAngle + d.startAngle) / 2 > Math.PI) ax *= -1;
let angle = (Math.PI / 2) - Math.atan2(-y, ax);
if (angle < 0) angle += 2 * Math.PI;
return {startAngle: angle, endAngle: angle};
}
outerLabel[d.data.label].newAngle = newAngle();
const interpolateOuterLabel = d3.interpolate(
outerLabel[d.data.label].currentAngle,
outerLabel[d.data.label].newAngle
);
return function (t) {
const position = midpoint(interpolateOuterLabel(t), labelRadius);
const [ax, y] = position;
const linkDistance = 5;
const label = (ax > 0)
? {dx: linkDistance, textAnchor: "start"}
: {dx: -linkDistance, textAnchor: "end"};
d3.select(g.selectAll(".link").nodes()[i])
.datum([
midpoint(interpolate(d)(t), outerRadius),
midpoint(interpolate(d)(t), outerRadius + linkDistance),
[ax, y],
[ax + label.dx, y]
])
.attr("d", lineGenerator);
d3.select(g.selectAll(".outer-label").nodes()[i])
.attr("dx", label.dx)
.style("text-anchor", label.textAnchor);
return "translate(" + position + ")";
};
}
const transition = d3.transition().duration(opts.duration);
if (opts.gradient.enabled) {
const gradient = defs.selectAll("radialGradient").data(data, function (d) { return d.label; });
const gradientEnter = gradient.enter().append("radialGradient")
.attr("gradientUnits", "userSpaceOnUse")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", "120%")
.attr("id", function (d, i) { return id + "-grad" + i; });
gradientEnter.append("stop")
.attr("class", "grad-stop-0")
.style("stop-color", function (d, i) { return pathColor(d, i); });
gradientEnter.append("stop")
.attr("class", "grad-stop-1")
.attr("offset", opts.gradient.percentage + "%");
defs.selectAll("radialGradient").select(".grad-stop-0")
.transition(transition)
.style("stop-color", function (d, i) { return pathColor(d, i); });
}
function key (d) { return d.data.label; }
const pie = d3.pie()
.sort(null)
.value(function (d) { return d.value; });
const sliceG = g.selectAll(".slice-g").data(pie(data), key);
const sliceGEnter = sliceG.enter().append("g")
.attr("class", "slice-g");
attachListeners(sliceGEnter);
sliceGEnter
.append("path")
.attr("id", function (d, i) { return id + "-slice" + i; })
.attr("class", "slice")
.attr("fill", function (d, i) {
return opts.gradient.enabled
? "url(#" + id + "-grad" + i + ")"
: pathColor(d.data, i);
});
sliceG
.exit()
.each(function (d, i) { data[i] = {value: 0, label: d.data.label}; });
pie(data).forEach(function (d, i) {
if (typeof currentData[d.data.label] === "undefined") {
const a = (i) ? currentData[pie(data)[i - 1].data.label].endAngle : 0;
currentData[d.data.label] = {startAngle: a, endAngle: a};
}
});
g.selectAll(".slice")
.data(pie(data), key)
.transition(transition)
.attrTween("d", arcTweenSlice)
.end()
.then(function () {
data = data.filter(function (d, i) { return (i === 0 || d.value); });
defs.selectAll("radialGradient").data(data, function (d) { return d.label; }).exit().remove();
g.selectAll(".slice-g").data(pie(data), key).exit()
.each(function (d) {
delete currentData[d.data.label];
delete outerLabel[d.data.label];
})
.remove();
for (const d of pie(data)) {
currentData[d.data.label] = d;
if (opts.labels.outer.format !== "none") {
outerLabel[d.data.label].currentAngle = outerLabel[d.data.label].newAngle;
}
}
})
.catch(function (error) { console.warn(error); }); // eslint-disable-line no-console
sliceGEnter.append("text")
.attr("class", "inner-label")
.attr("dy", ".35em");
function opacityTweenInnerlabels (d) {
if (!d.data.value) return function () { return 0; };
return function (t) {
const o = interpolate(d)(t);
const percentage = 100 * (o.endAngle - o.startAngle) / (2 * Math.PI);
return percentage < opts.labels.inner.hideWhenLessThanPercentage ? 0 : 1;
};
}
g.selectAll(".inner-label").data(pie(data), key)
.text(function (d) {
return (d.data.label === "undefined")
? "undefined"
: Math.round(100 * d.data.value / total) + "%";
})
.transition(transition)
.attrTween("opacity", opacityTweenInnerlabels)
.attrTween("transform", arcTweenInnerlabel);
if (opts.labels.outer.format !== "none") {
pie(data).forEach(function (d, i) {
if (typeof outerLabel[d.data.label] === "undefined") {
const a = (i) ? currentData[pie(data)[i - 1].data.label].endAngle : 0;
outerLabel[d.data.label] = {
currentAngle: {startAngle: a, endAngle: a},
newAngle: {startAngle: a, endAngle: a}
};
}
let fx = 0;
const [x, y] = midpoint(d, labelRadius);
if (d.data.value) {
fx = (x >= 0) ? opts.labels.outer.collideHeight : -opts.labels.outer.collideHeight;
}
nodes.push({fx, y});
});
d3.forceSimulation(nodes).alphaMin(0.5)
.force("collide", d3.forceCollide(opts.labels.outer.collideHeight / 2))
// Custom force to keep all nodes on a circle.
.force("boundY", function () {
for (const node of nodes) {
// Constrain the Y-position of the node to keep it on a circle.
node.y = limit(node.y);
}
})
.tick(30);
const outerLabelsGEnter = sliceGEnter
.append("g")
.attr("class", "outer-label-g");
outerLabelsGEnter.append("text")
.attr("class", "outer-label")
.attr("dy", ".35em")
.text(key);
outerLabelsGEnter.append("path")
.attr("class", "link");
g.selectAll(".outer-label-g").data(pie(data), key)
.transition(transition)
.style("opacity", function (d, i) { return (i && d.value) ? 1 : 0; })
// eslint-disable-next-line no-invalid-this
.each(function (d, i) { $(this).children(".link").attr("stroke", pathColor(d.data, i)); });
g.selectAll(".outer-label").data(pie(data), key)
.transition(transition)
.attrTween("transform", arcTweenOuterlabel);
}
};
}