PHPGraphLib Tutorial #1: Setup & Simple Example

Overview

To use PHPGraphLib:

  1. Make sure the PHP GD2 graphics extension is enabled.
  2. Include the source file "phpgraphlib.php" in a stand alone php script (no html here).
  3. Create a PHPGraphLib object.
  4. Add data using the addData() function.
  5. Customize graph using desired customization functions.
  6. Finalize graph using createGraph() function
  7. Include the above script as the source location of an image (<img src="my_graph_script.php">)

Include the source file "phpgraphlib.php" in a new script

To include the source PHPGraphLib class file, add this php include call at the top of your stand alone php script. This script will only include the PHP calls to create your graph. You will not include any HTML output in this script. Later, we will set the src="" element of an html image tag to the location of our new script on the desired page for our graph.

include("phpgraphlib.php");

Creating the PHPGraphLib Object

Next, you have to create a PHPGraphLib object. You may leave the arguments blank to use default dimensions, or you may specify your own width and height.

$graph = new PHPGraphLib(400,300);

Add data to the graph

To add data to the graph, call the addData() function on your PHPGraphLib object. You must specify an array as the argument to the addData() function as shown below. The values in the array will be used as y-axis values. If the array has keys, the keys will be used as x axis values.

$data = array("Alex"=>99, "Mary"=>98, "Joan"=>70, "Ed"=>90);
$graph->addData($data);

Customize the graph

In this example we have decided to give the graph a title, and set the y-axis values to be the color red. By default, all PHPGraphLib graphs are bar graphs, so we do not have to call anything special to display this.

$graph->setTitle("Test Scores");
$graph->setTextColor("blue");

Finalize the graph

After all customizations are done, we call the createGraph() function to finalize the graph. Now, you can close the php script and include the "?>" php tag.

$graph->createGraph();

Here is the whole script we created above:

<?php
include("phpgraphlib.php");
$graph = new PHPGraphLib(400,300);
$data = array("Alex"=>99, "Mary"=>98, "Joan"=>70, "Ed"=>90);
$graph->addData($data);
$graph->setTitle("Test Scores");
$graph->setTextColor("blue");
$graph->createGraph();
?>

Include the created script as the src of an image on the desired page

On the page you want the graph to appear, create an HTML image tag and set the src="" to the location of the script you created above.

<html>
<h3>This is where I want to display my graph</h3>
<img src="graph_bar.php" />
</html>

You're done! Here is the graph you just created:

example_graph_setup: example_graph_setup

Bullet For more advanced examples, view the Examples page