Build Lightweight HTML Graphs

calendar October 22, 2009

For simple bar graphs, you don’t need fancy images or flash movies, you can use this simple code to create bar graphs with HTML tables and PHP.

Code:

<html>
 <head>
 <title>HTML Graphs</title>
 </head>
 <?php
 $data = array(
 array('movies', 10),
 array('music', 20),
 array('games', 80),
 array('series', 40)
 );
 $max = 0;
 foreach($data as $dt)
 {
   $max += $dt[1];
 }
 ?>
 <body>
 <table width="400" cellspacing="0" cellpadding="2">
 <?php
 foreach($data as $dt)
 {
   $percent = ($dt[1]/$max)*100;
 ?>
 <tr>
 <td width="20%"><?=$dt[0]?></td>
 <td width="10%"><?=$dt[1]?>%</td>
 <td>
 <table width="<?=$percent?>%" bgcolor="#666666">
 <tr><td>&nbsp;</td></tr>
 </table>
 </td>
 </tr>
 <?php
 }
 ?>
 </table>
 </body>
 </html>

Photo:

Save the code as html_graphs.php

Colored bar graphs

If you want to add some color to the data use the next code.

Code:

<html>
 <head>
 <title>HTML Graphs</title>
 </head>
 <?php
 $data = array(
 array('movies', 10, '#ff0000'),
 array('music', 20, '#ff9900'),
 array('games', 80, '#006600'),
 array('series', 40, '#000000')
 );
 $max = 0;
 foreach($data as $dt)
 {
   $max += $dt[1];
 }
 ?>
 <body>
 <table width="400" cellspacing="0" cellpadding="2">
 <?php
 foreach($data as $dt)
 {
   $percent = ($dt[1]/$max)*100;
 ?>
 <tr>
 <td width="20%"><?=$dt[0]?></td>
 <td width="10%"><?=$dt[1]?>%</td>
 <td>
 <table width="<?=$percent?>%" bgcolor="<?=$dt[2]?>">
 <tr><td>&nbsp;</td></tr>
 </table>
 </td>
 </tr>
 <?php
 }
 ?>
 </table>
 </body>
 </html>

Photo:

Save the code as html_colored_graphs.php

admin

Leave a Reply

You must be logged in to post a comment.