// Drawing a Pie Chart of BMC Science Majors // The data... int[] nMajors; String[] majors; 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(); // Read data from a data file: SciMajors.txt // The data file should be created using a Plain Text Editor // It should be stored in the Data folder of the sketch // Read the data file as an array of strings, each line in a string. String[] lines = loadStrings("SciMajors.txt"); // Create the data arrays depending on how many lines were read from the data file println("Read " + lines.length + " entries from data file."); nMajors = new int[lines.length]; majors = new String[lines.length]; // Parse the strings in line[] into the data arrays for (int i = 0; i < lines.length; i++) { String[] pieces = split(lines[i], ","); majors[i] = pieces[0]; nMajors[i] = int(pieces[1]); } } // 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()