Tuesday, March 29, 2011

Excel based visualizations - bar graph

Finally got some data from a friend to work on. I am planning to use Processing for reading data from excel files and displaying them to identify patterns, in this case seasonal trends.

This code uses Java's native JFileChooser to pop up a dialog box and allows you to select an excel sheet from which to read from. It then reads a set of cell values (hard-coded for now, have to work on that), plots them and cycles through sheets on mouseClicked.

I was not able to see any seasonal trend as of now, maybe because the data set is on a monthly basis which may not be nearly the required sample rate. Anyway, to reduce the effect that increasing population (the data was from a rural health related survey), I have tried normalizing the data based on the average monthly value in the respective year, and scaling it up by an arbitrary amount.

I used Jer Thorp's concise and beautiful tutorial to get started. Please bear in mind that I'm a noob at programming (2 weeks in) so take anything you find in these posts with a grain of salt.


// Code begins here

import de.bezier.data.*;

int columnWidth = 30;
int sheetNumber = 0;

boolean flagNormalize = false;

float dataKM;
float dataKM_remapped;
float dataKM_sum = 0;

XlsReader reader;

PFont f;

void setup ()
{
size((12*columnWidth),300);
background(255);
stroke(0,0,0,0);
smooth();

button_Normalize.setSize(80,20);
button_Normalize.setLocation(30, 200);

f = loadFont("DejaVuSans-ExtraLight-48.vlw");

JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(chooser.getAcceptAllFileFilter());
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
println("You chose to open this file: " + chooser.getSelectedFile().getAbsolutePath());
}
reader = new XlsReader( this, chooser.getSelectedFile().getAbsolutePath() );
}

void refreshScreen(){
size((12*columnWidth),300);
background(255);
stroke(0,0,0,0);
}

void draw(){
reader.openSheet(sheetNumber);
fill(0);
if (!flagNormalize) text("Sheet " + sheetNumber, 30, 30);
if (flagNormalize) text("Sheet " + sheetNumber + " - Normalized",30, 30);

// Debug information for main variables
// println(flagNormalize);
// println(sheetNumber);

if (flagNormalize) {
dataKM_sum = 0;
for (int j=0; j<=11; j++){
dataKM = reader.getFloat((j+4),1);
dataKM_sum = dataKM_sum+dataKM;
}
}
for (int i=0; i<=11; i++){
dataKM = reader.getFloat((i+4),1);
if (flagNormalize) dataKM = (dataKM/dataKM_sum)*40000;
dataKM_remapped = map(dataKM,0,8000,10, (height-10));
fill(255,(dataKM/8000)*255,0);
rect((i*columnWidth),(height-10),columnWidth,(-1*dataKM_remapped));
}
noLoop();
}

void mouseClicked(){
if(sheetNumber<=3) sheetNumber++;
else if(sheetNumber>=3){
sheetNumber = 0;
flagNormalize = !flagNormalize;
}
// println(sheetNumber);
refreshScreen();
redraw();
}

No comments: