Creating a simple bar chart
You can checkout the example of the script here
First we need to add a question. You can remove this, it all depends on what your using this bar chart for.
CODE
<?php
// your question
$question = "What is your favorite pet survey.";
echo $question;
?>
Next we need to define some things. First is the width of the table or the graph, then the color of the graph, which I'm going to use grey. You may also use color codes. (e.g. #FFFFFF)
Next is what we're going to set our graphing variables into an array. This is what is going to display inside the table.
CODE
<?php
// total width
$total_width = 500;
// base color
$base_color = 'grey';
// add an array per field to show
$graphs = array(
array('label'=>'Dogs', 'color'=>'blue', 'amount'=>'30'),
array('label'=>'Cats', 'color'=>'green', 'amount'=>'35'),
array('label'=>'Birds', 'color'=>'red', 'amount'=>'25'),
array('label'=>'Other', 'color'=>'orange', 'amount'=>'10'),
);
?>
The array is used like so.
array('label'=>'LABEL NAME', 'color'=>'COLOR OF GRAPH AREA', 'amount'=>'THE AMOUNT OF THE GRAPH'),
Simple enough. Next comes the more advanced part. We're going to put that array into an loop then echo it out into a nice table graph.
CODE
<?php
for($x = 0; $x < count($graphs); $x++)
{
echo '
<table width="'.$total_width.'">
<tr>
<td colspan="2">
'.$graphs[$x]['label'].'
</td>
</tr>
<tr>
<td width="'.$graphs[$x]['amount'].'%" bgcolor="'.$graphs[$x]['color'].'">
'.$graphs[$x]['amount'].'%
</td>
<td width="'.(100-$graphs[$x]['amount']).'%" bgcolor="'.$base_color.'">
</td>
</tr>
</table>';
}
?>
Now what we're doing here is some basic math. 100 minus the amount on that certain row of the graph.
CODE
<?php
<td width="'.(100-$graphs[$x]['amount']).'%" bgcolor="'.$base_color.'">
?>
Very simple and basic php math.
Now here is our final code.
CODE
<?php
// your question
$question = "What is your favorite pet survey.";
echo $question;
// total width
$total_width = 500;
// base color
$base_color = 'grey';
// add an array per field to show
$graphs = array(
array('label'=>'Dogs', 'color'=>'blue', 'amount'=>'30'),
array('label'=>'Cats', 'color'=>'green', 'amount'=>'35'),
array('label'=>'Birds', 'color'=>'red', 'amount'=>'25'),
array('label'=>'Other', 'color'=>'orange', 'amount'=>'10'),
);
for($x = 0; $x < count($graphs); $x++)
{
echo '
<table width="'.$total_width.'">
<tr>
<td colspan="2">
'.$graphs[$x]['label'].'
</td>
</tr>
<tr>
<td width="'.$graphs[$x]['amount'].'%" bgcolor="'.$graphs[$x]['color'].'">
'.$graphs[$x]['amount'].'%
</td>
<td width="'.(100-$graphs[$x]['amount']).'%" bgcolor="'.$base_color.'">
</td>
</tr>
</table>';
}
?>
Saturday September 22, 2007 | http://www.totaldream.org/article/124-creating_a_simple_bar_chart.html