-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpie-chart.js
112 lines (82 loc) · 2.67 KB
/
pie-chart.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
function PieChart(x, y, diameter) {
this.x = x;
this.y = y;
this.diameter = diameter;
this.labelSpace = 30;
this.get_radians = function(data) {
var total = sum(data);
var radians = [];
for (let i = 0; i < data.length; i++) {
radians.push((data[i] / total) * TWO_PI);
}
return radians;
};
this.popup = function(index,data,colour,mouseOver){
var angles = this.get_radians(data);
var lastAngle = 0;
for (var i = 0; i < data.length; i++) {
noFill();
stroke(0);
strokeWeight(1);
arc(this.x, this.y,this.diameter, this.diameter,lastAngle, lastAngle + angles[i] + 0.001);
if(i==index){
fill(colour);
strokeWeight(2);
arc(this.x, this.y,this.diameter+30, this.diameter+30,lastAngle, lastAngle + angles[i] + 0.001);
}
lastAngle += angles[i];
}
}
this.draw = function(data, labels, colours, title) {//this.pie.draw(col, labels, colours, title);
// Test that data is not empty and that each input array is the
// same length.
if (data.length == 0) {
alert('Data has length zero!');
} else if (![labels, colours].every((array) => {
return array.length == data.length;
})) {
alert(`Data (length: ${data.length})
Labels (length: ${labels.length})
Colours (length: ${colours.length})
Arrays must be the same length!`);
}
// https://p5js.org/examples/form-pie-chart.html
var angles = this.get_radians(data);
var lastAngle = 0;
var colour;
for (var i = 0; i < data.length; i++) {
if (colours) {
colour = colours[i];
} else {
colour = map(i, 0, data.length, 0, 255);
}
fill(colour);
stroke(0);
strokeWeight(1);
arc(this.x, this.y,this.diameter, this.diameter,lastAngle, lastAngle + angles[i] + 0.001); // Hack for 0!
if (labels) {
this.makeLegendItem(labels[i], i, colour);
}
lastAngle += angles[i];
}
if (title) {
noStroke();
textAlign('center', 'center');
textSize(24);
text(title, this.x, this.y - this.diameter * 0.6);
}
};
this.makeLegendItem = function(label, i, colour) {
var x = this.x + 50 + this.diameter / 2;
var y = this.y + (this.labelSpace * i) - this.diameter / 3;
var boxWidth = this.labelSpace / 2;
var boxHeight = this.labelSpace / 2;
fill(colour);
rect(x, y, boxWidth, boxHeight);
fill('white');
noStroke();
textAlign('left', 'center');
textSize(12);
text(label, x + boxWidth + 10, y + boxWidth / 2);
};
}