Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryWeb Page and Site Features

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Making Bar Graphs On The Fly

Sometimes you have data that would be better expressed with graphical bars, a visual presentation.

For example, instead of (or in addition to) writing, "The group was composed of 540 women, 602 men, and 239 children," it could be expressed this way:

Women
 
Men
 
Children
 

Words and numbers can publish exact information. Graphical bars let the relationships be assimilated at a glance.

I'll show you two ways to make the graphical bars, with a background color and with an image. The PHP script generates and publishes the graphical bars and their labels on the fly with the information you provide.

Background color renders in every popular browser, even if images are blocked. Images, however, can have a texture that a plain background color does not.

Some printers can be directed to block background colors and/or images when printing a web page to paper. If that is a concern, the graphical bar can be bordered. Then, the border will print regardless and provide at least an outline of the graphical bar.

Let's get started.

The example script I'll give you is PHP. The data for the graphical bars can be hard coded into the script or, if it will be changing frequently, imported from a plain text file.

Whether hard coded or obtained from a file, the script uses the information to generate the graphical bars on the fly.

Below is what the example script will render. You'll see the same sets of numbers represented as graphical bars composed of a bordered background color and graphical bars composed of an image.

Graphed with bordered div and background color

Blue crayons
 
Red carpet with fringes
 
Purple place mats
 
White roses
 
Orange peel
 
Yellow business suits
 
Green eggs and ham
 

Graphed with sized image

Blue crayonsbar
Red carpet with fringesbar
Purple place matsbar
White rosesbar
Orange peelbar
Yellow business suitsbar
Green eggs and hambar

Below is the graphical bars PHP script.

Copy the script and paste it into a plain text processor. It can be uploaded to your server as is, if you wish to see the example run. To use it otherwise, you'll be making a few edits.

<?php
// Copyright 2008 Bontrager Connection, LLC

# Specify maximum bar length in pixels.
$MaximumBarLength = 225;

# The data.
$arrayOfThings = array();
array_push($arrayOfThings,'Blue crayons 49');
array_push($arrayOfThings,'Red carpet with fringes 54');
array_push($arrayOfThings,'Purple place mats 203');
array_push($arrayOfThings,'White roses 40');
array_push($arrayOfThings,'Orange peel 9');
array_push($arrayOfThings,'Yellow business suits 87');
array_push($arrayOfThings,'Green eggs and ham 79');

// Print set of graphs composed of background color in bordered div.
echo '<h3>Graphed with bordered div and background color</h3>';
CreateGraphWithDiv($arrayOfThings,$MaximumBarLength);

// Print set of graphs composed of sized image.
echo '<h3>Graphed with sized image</h3>';
CreateGraphWithImage($arrayOfThings,$MaximumBarLength);

// The function to print graphs composed of background color in bordered div.
// Class ".tdbar" can be changed in line about middle of function.
function CreateGraphWithDiv($anArray,$maxBarLength)
{
   $localArray = array();
   $largestValue = 0;
   foreach($anArray as $element)
   {
      if( ! preg_match('/\d/',$element) ) { continue; }
      $element = preg_replace('/\t/',' ',$element);
      $element = preg_replace('/\s*$/','',$element);
      $pieces = explode(' ',$element);
      $value = array_pop($pieces);
      $value = preg_replace('/\D*/','',$value);
      array_push($localArray,implode(' ',$pieces)."\t$value"); 
      if($value > $largestValue) { $largestValue = $value; }
   }
   $valueMultiplicand = $maxBarLength / $largestValue;
   echo '<style type="text/css">';
   echo '.tdbar { height:11px; background-color:#6B8FC4; color:white; border-style:solid; border-width:1px; border-color:black; font-size:1px; line-height:1px }';
   echo '</style>';
   echo '<table border="0" cellpadding="5" cellspacing="0">';
   foreach($localArray as $element)
   {
      list($item,$value) = explode("\t",$element);
      echo "<tr><td>$item</td>";
      echo '<td><div class="tdbar" style="width:';
      echo intval($value * $valueMultiplicand);
      echo 'px;"> </div></td></tr>';
   }
   echo '</table>';
} # function CreateGraphWithDiv()

// The function to print graphs composed of sized image.
// Image URL near top of function needs to be customized.
// Image border can be changed in line near bottom of function.
function CreateGraphWithImage($anArray,$maxBarLength)
{
   $imageURL = '/images/hdrbg.jpg';
   $localArray = array();
   $largestValue = 0;
   foreach($anArray as $element)
   {
      if( ! preg_match('/\d/',$element) ) { continue; }
      $element = preg_replace('/\t/',' ',$element);
      $element = preg_replace('/\s*$/','',$element);
      $pieces = explode(' ',$element);
      $value = array_pop($pieces);
      $value = preg_replace('/\D*/','',$value);
      array_push($localArray,implode(' ',$pieces)."\t$value"); 
      if($value > $largestValue) { $largestValue = $value; }
   }
   $valueMultiplicand = $maxBarLength / $largestValue;
   echo '<table border="0" cellpadding="5" cellspacing="0">';
   foreach($localArray as $element)
   {
      list($item,$value) = explode("\t",$element);
      echo "<tr><td>$item</td>";
      echo '<td><img src="'.$imageURL.'" width="';
      echo intval($value * $valueMultiplicand);
      echo '" height="13" border="0" alt="bar"></td></tr>';
   }
   echo '</table>';
} # function CreateGraphWithImage()
?>

Notice two places marked for customization.

The first place is where the maximum length of the graphical bars is specified. The script automatically determines graphical bar lengths so the largest numerical value is represented by a bar at the maximum length (or one pixel shorter, depending on how rounding affects the result). The rest of the bars are proportionate to the rest of the numerical values.

The second place for customization is where the data is provided. Let me talk about that.

The first line creates an empty array. You don't have to do anything with that, or even understand it. Just leave the line as is.

The next lines insert the information into the array. The information is between single quotes (apostrophes) and end with a space and then a number. If the information itself contains a single quote character, the single quote must be escaped with a leading backward slash character. Example:

array_push($arrayOfThings,'Will\'s days per week 8');

The information can have any text leading up to the number. What is important is that the line of information ends with a space or a tab character followed by a number. The number will be used to determine the length of the graphical bar and the text on the line before the number will be used for the label.

Those are the primary customizations.

Other customizations are:

  • Deciding which of the two functions to run, the one creating the graphical bar with a background color or the one creating the bar with an image.

  • Whether or not to put a border around the graphical bar.

  • The color of the graphical bar (when appropriate).

  • Which image to use (when appropriate).

  • The thickness of the graphical bar.

The points where those edits can be made are mentioned in the source code of the script.

Graphical Bars On The Fly From A Data File

To make the script generate graphical bars on the fly from information in an external data file, make the data file and then modify the script.

Below is the content of a data file with the same information as the example script. Use it for testing or create your own information.

Notice that the information follows the same rule of each line of information ending with a space (or tab) and a number.

Blue crayons 49
Red carpet with fringes 54
Purple place mats 203
White roses 40  
Orange peel 9
Yellow business suits 87
Green eggs and ham 79

The file can be updated manually as appropriate or updated automatically with some other software.

Blank lines are okay. They will be ignored.

Also, lines of text with no digits will be ignored. It is a way of inserting comments into the file that don't get translated into a graph.

Now, let's modify the script itself.

In the example script, replace this:

# The data.
$arrayOfThings = array();
array_push($arrayOfThings,'Blue crayons 49');
array_push($arrayOfThings,'Red carpet with fringes 54');
array_push($arrayOfThings,'Purple place mats 203');
array_push($arrayOfThings,'White roses 40');
array_push($arrayOfThings,'Orange peel 9');
array_push($arrayOfThings,'Yellow business suits 87');
array_push($arrayOfThings,'Green eggs and ham 79');

With this:

# Specify the location of the external file containing the data.
$DataFile = $_SERVER['DOCUMENT_ROOT'].'/subdirectory/myFile.txt';
$arrayOfThings = file($DataFile);

On the $DataFile = ... line, replace /subdirectory/myFile.txt with the location of your data file.

Test it to verify it works as it should. Then you're good to go.

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC