Charting Weight Change With Google Visualizations
I started trying to lose weight a while back, since we both know I’m a bit heavy and sitting in front of a computer isn’t going to lose the weight for me.
Naturally, it’s important that I incorporate technology into my weight loss somehow, right? So I decided to give the Google Visualizations API a spin.
I worked up a quick data format and a method to pop the data out. Nothing fancy, just a fixed width flat file. This doesn’t deserve a database.
1 2 |
2010-06-30 235.4 2010-06-29 236.8 |
Easy to read, easy to edit, and easy to consume. Every morning I just hop on the server, add the day’s weight and log off.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php // Get the max days back we want to look. $max_days = 7; if( isset( $_REQUEST['days'] ) and ! empty( $_REQUEST['days'] ) ) $max_days = intval( $_REQUEST['days'] ); $i = 0; $lines = array(); $fh = fopen( 'data.txt', 'r' ); while( ! feof( $fh ) and ++$i <= $max_days ) { $line = fgets( $fh ); if( empty( $line ) ) { continue; } array_unshift( $lines, $line ); } fclose( $fh ); |
Now I just needed to represent it. The API is very object oriented and easy to work with. I wish there was a less verbose way of presenting the data, but you can’t have everything.
Actually, there may be a better way, I just didn’t come across it while speed reading the docs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
function drawChart() { var data = new google.visualization.DataTable(); data.addColumn( 'string', 'Date' ); data.addColumn( 'number', 'Weight' ); data.addRows( <?php echo count( $lines ); ?> ); <?php $i = 0; foreach( $lines as $line ): ?> data.setValue( <?php echo $i; ?>, 0, '<?php echo substr( $line, 0, 10 ); ?>' ); data.setValue( <?php echo $i; ?>, 1, <?php echo floatval( substr( $line, 11 ) ); ?> ); <?php ++$i; endforeach; ?> var chart_div = document.getElementById( 'chart_div' ); var chart = new google.visualization.LineChart( chart_div ); chart.draw( data, { width: 800, height: 600, title: 'Weight Over Time' } ); } |
And there you have it, fancy charting in no time.
See it in action at http://static.velvetcache.org/weight.php
Get the full source at http://gist.github.com/459148.