Graphing in PHP


If you want to draw dynamic graphs, you CAN do so using PHP.

You'll need to have your PHP loaded with the GD graphics library (pretty much a standard), the use something like Phplot which we've used on this page.

The web page you're viewing at the moment is a piece of HTML that can be generated anyhow - the important thing is that it calls up an image which is a link to the PHP graphing script. The tag used above to call up the graph is
<img src=tsales.php>

The source of that demonstration script is as follows:

<? 
include ( "phplot.php");
$graph = new PHPlot;

$graph->SetDataType"linear-linear");

// Specify some data
$data = array(
    array(  
""1999,     3637),
    array(  
""2000,    3267),
    array(  
""2001,    13701),
    array(  
""2002,    19135),
    array(  
""2003,    20841),
    array(  
""2004,     27435)
);
$graph->SetDataValues($data);

//Specify plotting area details
$graph->SetPlotType"lines");
$graph->SetTitleFontSize"4");
$graph->SetTitle"Train tickets to and from Melksham");
$graph->SetPlotAreaWorld(1998,0,2007,35000);
$graph->SetPlotBgColor"white");
$graph->SetPlotBorderType"left");
$graph->SetBackgroundColor"white");

//Define the X axis
$graph->SetXLabel"Year");
$graph->SetHorizTickIncrement"1");

//Define the Y axis
$graph->SetVertTickIncrement"5000");
$graph->SetPrecisionY"0");
$graph->SetLightGridColor"blue");

$graph->SetDataColors( array( "red"), array( "black") );

$graph->DrawGraph();

?>


When you call up this current page from your browser, a futher request is made back to the server for the image which is then dynamically generated and sent to the browser for display as a portable network graphic (.png) file.

Please note that the generation of graphs on the server could have performance issues if your site will be generating a high volume of such pages. But if you're only looking at a few dozen graphs every minute, you won't come even close to a problem.

Well House Consultants provides training in Open Source technologies such as PHP - this page is a sample that was written during a course to illustrate how PHP can be used to generate graphs on the fly. In a complete application, data would be read from file, database or other source - all things we teach.
PHPlot can be downloaded from here
This page by Well House Consultants, 2024