// Pie Chart visualization of births by weekday
// Now using arrays...and added data labels/legend etc.
// The data variables...
// sun, mon, tue, wed, thu, fri, sat
int[] data = {
5, 5, 1, 4, 4, 4, 8
};
String[] labels = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
int total;
float[] perc = new float[7];
// The sketch variables
float cx, cy, pieDia;
float startAngle, stopAngle;
color [] colors = {
color(238, 118, 0), // sunday
color(123, 165, 248),
color(7, 57, 1),
color(255, 246, 63),
color(255, 0, 0),
color(0, 255, 0),
color(0, 0, 255) // saturday
};
void setup() {
size(500, 500);
background(255);
smooth();
// process
// compute the total population
total = 0;
for (int i=0; i < data.length; i++) {
total += data[i];
}
// compute percentages
for (int i=0; i < data.length; i++) {
perc[i] = float(data[i])/total;
}
// pie variables
cx = width/2;
cy = height/2;
pieDia = 250;
noLoop();
} // setup()
void draw() {
startAngle = 0;
stopAngle = 0;
for (int i=0; i < perc.length; i++) {
// set up pie parameters for ith slice
startAngle = stopAngle;
stopAngle = startAngle + TWO_PI*perc[i];
// dra the pie
noStroke();
fill(colors[i]);
arc(cx, cy, pieDia, pieDia, startAngle, stopAngle);
}
// draw legend
// draw title
fill(0);
textSize(24);
rectMode(CENTER);
text("Births by day of week (data in %)", 50, 50);
// legend variables
float w = 20, h = 20;
float x = 25;
float y = height-((h+5)*data.length);
rectMode(CORNER);
for (int i=0; i < perc.length; i++) {
stroke(0);
fill(colors[i]);
rect(x, y, w, h);
fill(0);
textSize(12);
text(labels[i], x+w+5, y+h);
y += h+5;
}
} // draw()