// Drawing a Pie Chart of BMC Science Majors
// The data...
int[] nMajors = {92, 72, 49, 52, 22, 22, 17, 15};
String[] majors = {"Psychology", "Mathematics", "Biology", "CS",
"Physics", "BioChem", "Chemistry", "Geology"};
color[] pallette = {color(247,102,102), color(254,255,64), color(255,64,246),
color(30,214,6), color(214,6,6), color(74,150,252),
color(74,252,221), color(116,119,160)};
void setup() {
size(600, 600);
background(255);
textSize(12);
noLoop();
} // setup()
void draw() {
// Compute total;
int total = 0;
for (int i = 0; i < nMajors.length; i++) {
total = total + nMajors[i];
}
println("Total = " + total);
// Compute percentages
float[] perc = new float[nMajors.length];
for (int i = 0; i < perc.length; i++) {
perc[i] = float(nMajors[i])/total;
}
println(perc);
// Set up Pie
float cx = width/2;
float cy = height/2;
float sz = height/2;
// Draw the chart
float startAngle = 0, stopAngle;
for (int i = 0; i < perc.length; i++) {
// Draw the ith slice of the pie
stopAngle = startAngle + 2 * PI * perc[i];
fill(pallette[i]);
arc(cx, cy, sz, sz, startAngle, stopAngle);
startAngle = stopAngle;
}
// Draw legend
float x = 20, y = height/2;
for (int i = 0; i < majors.length; i++) {
fill(pallette[i]);
square(x, y, 20);
fill(0);
text(majors[i], x+30, y+20);
y = y + 30;
}
} // draw()
void pieChart(float[] a) {
// Now write a function that draws a pie chart...
} /// pieChart()