// Names and consumption of various energy sources String[] energySource; float[] consumption;
color[] swatch = {color(247, 87, 87), color(247, 240, 87), color(97, 87, 247), color(247, 87, 232), color(87, 247, 88), color(26, 11, 162)};
void setup() { size(600, 500); background(255);
// Read Data String[] lines = loadStrings("EnergyData.txt"); println("Read " + lines.length + " lines.");
// Parse Data energySource = new String[lines.length]; consumption = new float[lines.length];
for (int i=0; i < lines.length; i++) { // split each line into pieces String[] pieces = split(lines[i], ",");
energySource[i] =pieces[0]; consumption[i] = float(pieces[1]); } println("...parsed."); } // setup()
void draw() { background(255); drawBarGraph(energySource, consumption); } // draw()
void drawBarGraph(String[] legend, float[] data) { float x = 0.1*width; float y = 0.7*height; float delta = 0.8*width/data.length; float w = 0.95*delta;
for (int i=0; i < data.length; i++) { // compute the height of bar float h = map(data[i], 0, 100, 0, 0.7*height);
// Draw bar if (inBox(mouseX, mouseY, x, y, w, h)) { fill(255, 0, 0); rect(x, y-h, w, h); fill(0); textAlign(CENTER); text(data[i], x+w/2, y-h-10); } else { fill(0); rect(x, y-h, w, h); }
// Draw name of data item textAlign(CENTER); text(legend[i], x+w/2, y+20);
x = x + delta; } } // drawBarGraph()
boolean inBox(float px, float py, float x, float y, float w, float h) { return (px >=x && px <= x+w && py >= y-h && py <= y); } // inBox()
void drawPie(String[] legend, float[] data) { int pieX = width/2; int pieY = height/2; int pieSize = 250;
float startAngle = 0.0; // Pie variables float stopAngle = 0;
int legendX = width-150; int legendY = 150; int legendDelta = 26;
textSize(24);
for (int i=0; i < data.length; i++) { // Size of i-th pie slice stopAngle = startAngle + data[i]*TWO_PI/100.0;
// Draw i-th pie slice fill(swatch[i]); noStroke(); arc(pieX, pieY, pieSize, pieSize, startAngle, stopAngle);
// Draw Legend text(legend[i], legendX, legendY); legendY += legendDelta;
// update for next pie slice startAngle = stopAngle; }
fill(0); text("Energy Consumption\n% of Energy Sources\n(USA, 2005)", 75, 400); } // drawPie()