Building a Bar Graph in PHP
Tuesday, February 17th, 2009Can I be honest? I hate making graphs. I think they are over used and serve as filler on droll reports more often than not. In spite of that, I know they have their place. When used correctly can be a GREAT way to communicate a large amount of information in a very orderly way.
I needed a graph the other day to present some data, so I sat down and creating one from scratch. I’d like to share the experience for those of you who are trying to learn PHP. I am sure there are better ways to do this from a programming perspective, but I think it’s pretty easy for the rest of us to understand.
First, we create our script and for illustration purposes we simulate a data source. This can be static as I have done, or can be a query array return or just about any other source.
<?php
$tw=‘90%’;
$chart =
array(
rand(0,100),rand(0,100),rand(0,100),rand(0,100),rand(0,100));
$label = array(‘Frogs’,‘Lizards’,‘Gophers’,‘Snakes’,‘Turtles);
$cname=‘Likelihood of Creatures Being Eaten’;
//$label=array with labels
//$chart=array with percentages
//$tw=table width in percent or px
//$cname=table name
//barc($label,$chart,$tw,$cname);function barc($label,$chart,$cname,$tw=‘95%’){
echo ‘<table style=”border-collapse: collapse; border-right: 5px #c0c0c0 solid;border-left: 5px #c0c0c0 solid;border-bottom: 5px #c0c0c0 solid;border-top: 0px #c0c0c0 solid; width: ‘.$tw.‘; margin: 0px auto;”><tr><td style=”background-color: #c0c0c0; width: 10%;”>’;
echo ‘<table style=”border-collapse: collapse;width: 100%;”>’;
foreach ($label as $c){
$lab=$c;
echo ‘<tr><td style=”font-weight: bold; vertical-align: bottom; background-color: #c0c0c0;height: 20px;padding: 0px;margin: 0px;border-top: 3px #c0c0c0 solid;
font-size: 16px;”>’.$lab.‘</td>
</tr>
‘;
}
echo ‘</table>’;
echo ‘</td><td style=”background-color: #c0c0c0; width: 90%;”>’;echo ‘<table style=”border-collapse: collapse;width: 100%;”><tr>’;
$w=0;
while($w<100){
echo ‘<td style=”width: 1%;”></td>’;
$w++;
}
echo ‘</tr>’;
$x=1;
foreach ($chart as $c){
$bar=$c;
$fill=100-$bar;
if($x==7){$x=1;}
echo ‘<tr><td class=”bar” colspan=”‘.$bar.‘”style=”background : red url(bar’.$x.‘.jpg) repeat-x top center;
background-color: red; height: 20px; width: 1%; padding: 0px; margin: 0px;
border-top: 3px #c0c0c0 solid; font-size: 16px;”>
<span style=”color: white; margin-left: 2px;”>’.$bar.‘%</span></td>
<td colspan=”‘.$fill.‘” style=”background-color: #c0c0c0;border-top: 3px #c0c0c0 solid;”></td>
</tr>’;
$x++;
}
echo ‘</table>’;echo ‘</td></tr><tr><td colspan=”3″ style=”background-color: #c0c0c0; font-size: 24px; text-align: center;”>’.$cname.‘</td></tr></table>’;
}
barc($label,$chart,$cname);
?>