-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPieChart.js
More file actions
396 lines (314 loc) · 12.3 KB
/
PieChart.js
File metadata and controls
396 lines (314 loc) · 12.3 KB
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
/*globals palette*/
//import {SizeChart} from './SizeChart.js';
// Based on D3 example: https://observablehq.com/@d3/zoomable-sunburst
// d3 label center: https://observablehq.com/@kerryrodden/sequences-sunburst
// data variable is loaded from data.json (header)
// Optional todo: https://stackoverflow.com/questions/29978957/transitions-in-d3-on-load
// Basically create the graph with empty values and then fill with transition
class PieChart {
constructor(originalData){
this.currentData = null;
this.originalData = originalData;
this.sizeChart = undefined;//new SizeChart();
}
// Create the pie chart
runApp(htmlContainer,data,d3, title, measure, unit){
var that = this;
this.currentData = data;
const root = partition(data);
var color = d3.scaleOrdinal(d3.quantize(d3.interpolateRainbow, data.children.length + 1));
var format = d3.format(",d");
var width = 600;
var radius = width / 6;
var arc = d3.arc()
.startAngle(d => d.x0)
.endAngle(d => d.x1)
.padAngle(d => Math.min((d.x1 - d.x0) / 2, 0.005))
.padRadius(radius * 1.5)
.innerRadius(d => d.y0 * radius)
.outerRadius(d => Math.max(d.y0 * radius, d.y1 * radius - 1));
root.each(d => d.current = d);
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, width])
.style("font", "15px sans-serif");
// Center label
const centerLabel = svg
.append("text")
.attr("text-anchor", "middle")
.attr("fill", "#888")
//.style("visibility", "hidden");
// Title
centerLabel
.append("tspan")
.attr("x", width/2)
.attr("y", width/2)
.attr("dy", "-2.2em")
.text(title || "Pesca per ports");
// Breadcrumb
centerLabel
.append("tspan")
.attr("x", width/2)
.attr("y", width/2)
.attr("dy", "-1.2em")
.attr("font-size", "0.8em")
.attr("fill", "black")
.attr("class", "breadcrumb")
.text("");
// Selected
centerLabel
.append("tspan")
.attr("x", width/2)
.attr("y", width/2)
.attr("dy", "0.3em")
.attr("font-size", "0.9em")
.attr("fill", "black")
.attr("class", "centerText")
.text("");
// Measure
centerLabel
.append("tspan")
.attr("x", width/2)
.attr("y", width/2)
.attr("dy", "2.2em")
.attr("font-size", "0.8em")
.text(measure || "Biomassa");
// Units
centerLabel
.append("tspan")
.attr("x", width/2)
.attr("y", width/2)
.attr("dy", "3.5em")
.attr("font-size", "0.8em")
.attr("class", "biomassText")
.text(format(root.value) + " " + (unit||"kg / km2"));
// Pie chart
const g = svg.append("g")
.attr("transform", `translate(${width / 2},${width / 2})`);
const path = g.append("g")
.selectAll("path")
.data(root.descendants().slice(1))
.join("path")
//.attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); })
.attr("fill", d => {return palette[d.data.species] === undefined ? 'rgb(50, 50, 50)' : "rgb(" + palette[d.data.species].color + ")"})// returns 'rgb(1,1,1)'
.attr("fill-opacity", d => arcVisible(d.current) ? (d.children ? 0.6 : 0.4) : 0.1)//0) // Here if you want to show other levels
.attr("d", d => arc(d.current));
path//.filter(d => d.children)
.style("cursor", "pointer")
.on("click", clicked);
path.on("mouseenter", mouseOnPath)
.on("mouseleave", mouseOffPath);
path.append("title")
.text(d => `${d.ancestors().map(d => d.data.species).reverse().join("/")}\n${format(d.value)}` + " kg/km2"); // TODO show label, modify label https://chartio.com/resources/tutorials/how-to-show-data-on-mouseover-in-d3js/#creating-a-tooltip-using-the-title-tag
const label = g.append("g")
.attr("pointer-events", "none")
.attr("text-anchor", "middle")
.style("user-select", "none")
.selectAll("text")
.data(root.descendants().slice(1))
.join("text")
.attr("dy", "0.35em")
.attr("fill-opacity", d => +labelVisible(d.current))
.style("font", d => (d.x1 - d.x0) < 0.01 ? (d.x1-d.x0)*100 * 15 +"px sans-serif" : "15px sans-serif")//(d.y1 - d.y0) * (d.x1 - d.x0) > 0.03 ? "15px sans-serif" : "8px sans-serif")
.attr("transform", d => labelTransform(d.current, d.target))
.text(d => d.data.name);
const parent = g.append("circle")
.datum(root)
.attr("r", radius)
.attr("fill", "none")
.attr("pointer-events", "all")
.on("click", clicked);
function clicked(event, p) {
// Create pop-up with length frequency for specie
if (p.children === undefined){
if (p.depth < 3) // No depth (only commercial/rebuig/restes)
that.sizeChart.createGraphInterface(p.data.species, p.parent.parent.data.name, undefined, event); // Port or Season, Zona or Year
else
that.sizeChart.createGraphInterface(p.data.species, p.parent.parent.data.name, p.parent.parent.parent.data.name, event); // Port or Season, Zona or Year
return;
}
parent.datum(p.parent || root);
root.each(d => d.target = {
x0: Math.max(0, Math.min(1, (d.x0 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
x1: Math.max(0, Math.min(1, (d.x1 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
y0: Math.max(0, d.y0 - p.depth),
y1: Math.max(0, d.y1 - p.depth)
});
// Show biomass
centerLabel
.select(".biomassText")
.style("visibility", null)
.text(format(p.value) + " kg / km2");
// Hide center mouse hover label
centerLabel
.select(".centerText")
.style("visibility", "hidden")
.text("")
// Breadcrumb
let bcrumbstr = "";
p.ancestors().reverse().forEach((item,i) => bcrumbstr += (i == 0 || i == p.ancestors().length-1 || i > 2) ? "" : item.data.name + " > ");
centerLabel
.select(".breadcrumb")
.text(bcrumbstr)
const t = g.transition().duration(750);
// Transition the data on all arcs, even the ones that aren’t visible,
// so that if this transition is interrupted, entering arcs will start
// the next transition from the desired position.
path.transition(t)
.tween("data", d => {
const i = d3.interpolate(d.current, d.target);
return t => d.current = i(t);
})
.filter(function(d) {
return +this.getAttribute("fill-opacity") || arcVisible(d.target);
})
.attr("fill-opacity", d => arcVisible(d.target) ? (d.children ? 0.6 : 0.4) : 0.1)//0) // Here if you want to show other levels
.attrTween("d", d => () => arc(d.current));
label.filter(function(d) {
return +this.getAttribute("fill-opacity") || labelVisible(d.target);
}).transition(t)
.attr("fill-opacity", d => +labelVisible(d.target))
.style("font", d => { // Modify font for small portions
let percentage = 100*(d.target.x1 - d.target.x0)/(2*Math.PI);
return percentage < 2 ? Math.max(15*percentage/2,9)+"px sans-serif" : "15px sans-serif";
})
.attrTween("transform", d => () => labelTransform(d.current, d.target));
}
// Show information about the path when mouse hover
function mouseOnPath(event, p){
if (p.current.y0 % 1 != 0) // During transition
return;
// Show biomass
centerLabel
.select(".biomassText")
.style("visibility", null)
.text(format(p.value) + " kg / km2");
centerLabel
.select(".centerText")
.style("visibility", null)
.text(p.data.species || p.data.name)
// Get the ancestors of the current segment, minus the root
const sequence = [];
let pCenter = p;
for (let i = 0; i<Math.floor(p.current.y0); i++){
sequence.push(pCenter);
pCenter = pCenter.parent;
}
// Highlight ancestors
path.attr("fill-opacity", d =>
sequence.indexOf(d) >= 0 ? 0.8 : arcVisible(d.current) ? (d.children ? 0.6 : 0.4) : 0.1
);
// Hide center label node
label.attr("fill-opacity", d =>
(pCenter == d ) ? 0 : +labelVisible(d.current)
);
}
function mouseOffPath(event, p){
if (p.current.y0 % 1 != 0) // During transition
return;
let pCenter = p;
const sequence = [];
// Find element on center
for (let i = 0; i<Math.ceil(p.current.y0); i++){
sequence.push(pCenter);
pCenter = pCenter.parent;
}
// Unhighlight ancestors
path.attr("fill-opacity", d =>
sequence.indexOf(d) >= 0 ? 0.6 : arcVisible(d.current) ? (d.children ? 0.6 : 0.4) : 0.1
);
// Show center label node
label.attr("fill-opacity", d =>
pCenter == d ? 1 : +labelVisible(d.current)
);
// Show center label biomass
centerLabel
.select(".biomassText")
.style("visibility", null)
.text(format(pCenter.value) + " kg / km2");
centerLabel
.select(".centerText")
.style("visibility", "hidden")
.text("")
}
function arcVisible(d) {
return d.y1 <= 3 && d.y0 >= 1 && d.x1 > d.x0;
}
function labelVisible(d) {
return d.y1 <= 3 && d.y0 >= 0 && (d.y1 - d.y0) * (d.x1 - d.x0) > 0.03; // Make the base label appear
//return d.y1 <= 3 && d.y0 >= 1 && (d.y1 - d.y0) * (d.x1 - d.x0) > 0.03;
}
function labelTransform(d, target) {
const x = (d.x0 + d.x1) / 2 * 180 / Math.PI;
const y = (d.y0 + d.y1) / 2 * radius;
// Make the base label go to center
if (target === undefined)
return `rotate(${x - 90}) translate(${y},0) rotate(${x < 180 ? 0 : 180})`; // Default
else if (d.y0 < 1 && target.y0 <= 1) // Rotate base label to be horizontal
return "rotate("+ (x - 90*d.y0) +") translate("+y*d.y0+",0) rotate("+(x < 180 ? 0 : 180)+")";
else
return `rotate(${x - 90}) translate(${y},0) rotate(${x < 180 ? 0 : 180})`; // Default
}
function partition(data){
const root = d3.hierarchy(data)
.sum(d => d.value) // Assing a value to each partition, based on the value of the smallest items
.sort((a, b) => b.value - a.value) // Organize partitions (here from big to small)
.sort((a, b) => b.data.name == "Others" ? -1 : 1)
return d3.partition()
.size([2 * Math.PI, root.height + 1])
(root);
}
//return svg.node();
// Remove loader class
htmlContainer.className = "my-4 w-100 mx-auto";
htmlContainer.appendChild(svg.node());
}
// Processes a basic sample with maximum categories being Comercial/Resta/Rebuig
processSample(inData){
const outData = {};
outData.children = [];
// Iterate over all rows
for (let i = 0; i<inData.length; i++){
let item = inData[i];
let nomEspecie = item.NomEspecie;
let nomComu = item.NomCatala || item.NomComu || item.NomEspecie;
let classCaptura = item.ClassificacioCaptura;
let biomass = item.Biomassa_Kg_Km2 || item.Biomassa;
if (biomass < 0.01) // Do not display items with little biomass
continue;
// Create ClassificacioCaptura level if it does not exist
if (outData.children.find(child => child.name === classCaptura) === undefined)
outData.children.push({"name": classCaptura, "children": [], "species": classCaptura});
let classIndex = outData.children.findIndex(child => child.name === classCaptura)
// Assign biomass value
outData.children[classIndex].children.push({"name": nomComu, "value": biomass, "species": nomEspecie});
}
this.originalData = outData;
return outData;
}
// Processes biomass data for a specific port
processPortBiomass(inData, portName){
const outData = {};
outData.children = [];
// Iterate over all rows
for (let i = 0; i<inData.length; i++){
let item = inData[i];
let nomEspecie = item.NomEspecie;
let nomComu = item.NomCatala || item.NomComu || item.NomEspecie;
let classCaptura = item.ClassificacioCaptura;
let biomass = item.Biomassa_Kg_Km2 || item.Biomassa;
if (biomass < 0.01) // Do not display items with little biomass
continue;
if (portName != item.NomPort)
continue;
// Create ClassificacioCaptura level if it does not exist
if (outData.children.find(child => child.name === classCaptura) === undefined)
outData.children.push({"name": classCaptura, "children": [], "species": classCaptura});
let classIndex = outData.children.findIndex(child => child.name === classCaptura)
// Assign biomass value
outData.children[classIndex].children.push({"name": nomComu, "value": biomass, "species": nomEspecie});
}
this.originalData = outData;
return outData;
}
}
//export {PieChart}