Forum Moderators: coopster

Message Too Old, No Replies

Drawing a histogram or bar chart

Historgrams using PHP

         

s9901470

11:35 am on Nov 17, 2005 (gmt 0)

10+ Year Member



Hi

I have a table with a variable 'age' and I want to select the data and draw a histogram or bar chart of the number in each category, using stars like this:

20-25 ****
26-3 *********
31-45 **

Could anyone give me an example of how to write this in PHP / MySQL?

Many thanks

Receptional Andy

3:55 pm on Nov 17, 2005 (gmt 0)



A google search for PHP histogram class [google.com] might give you some ideas.

Timotheos

6:41 pm on Nov 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I love a little puzzle.

$AGE_BRACKET = 5;
$START_AGE = 15;
$TOP_AGE = 100;

$sql = "SELECT age, count(age) as agenumber FROM people GROUP BY age";
$result = mysql_query($sql);

$bracketCount = array();
while ($row = mysql_fetch_assoc($result)) {
if ($row['age'] >= $START_AGE) {
$division = ceil($row['age'] / $AGE_BRACKET)-1;
$bracketCount[$division] += $row['agenumber'];
}
}

for ($lowerBracket = $START_AGE; $lowerBracket < $TOP_AGE; $lowerBracket=$lowerBracket+$AGE_BRACKET) {
$upperBracket = $lowerBracket+$AGE_BRACKET-1;
$bracketTotal = $bracketCount[$lowerBracket/($AGE_BRACKET)];
echo $lowerBracket . " - " . $upperBracket . " ";
for ($i = 0; $i < $bracketTotal; $i++) {
echo "*";
}
echo "<br>";
}

What I like to do is put it in a table so the histogram lines up nicely and then instead of asterisks use a small gif maybe 5x10 and echo out the image file instead. They'll all nicely stack up to look like a bar chart.

s9901470

11:19 am on Nov 22, 2005 (gmt 0)

10+ Year Member



Thanks Timotheos, that works great!

What if I wanted to count categorical variables e.g. region as well?

Timotheos

11:59 pm on Nov 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sweet! I love it when a plan comes together ;-)

The age bracket thingy is what made it tougher. Any other variable would be easier.

$sql = "SELECT region, count(region) as regioncount FROM people GROUP BY region";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
echo $row['region'] . ' ';
for ($i = 0; $i < $row['regioncount']; $i++) {
echo "*";
}
echo "<br>";
}

s9901470

6:26 pm on Dec 15, 2005 (gmt 0)

10+ Year Member



Some of the rows now have too many asterisks. Is there a way to make one asterisk represent 5 people instead of 1 person?

Timotheos

7:52 pm on Dec 15, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well the simple way to do what you ask is divide by five.

for ($i = 0; $i < ($row['regioncount']/5); $i++) {
echo "*";
}