The Complete Magazine on Open Source

Creating Graphs Using PHP

, / 767 0


Graphs can be created in several ways, ranging from manual to the use of computers and sophisticated graph-drawing software packages. This article gives a brief description of the use of PHP to draw graphs and, in particular, the JpGraph package.

There are many software packages that help create graphs and charts using PHP. One such package is JpGraph. It is released under a dual licence – the QPL 1.0 (Qt Free License) for open source or educational use, and the JpGraph Professional License for commercial use. Let’s discuss the open source version of JpGraph in this article.

The package can be downloaded from Currently, there are two different packages for PHP4 and PHP5. Select the appropriate link. You may extract the files anywhere, preferably in the document root (e.g., /var/www).
In order to use JpGraph, you will also have to download the gd library for PHP:

sudo apt-get install php5-gd

To check whether the library has been installed properly, type the following command:

php5 -m

You should see gd in the list. See Figure 1.
That’s it! Now we can start creating graphs.

Figure 1

Figure 1: gd in the list of installed libraries

Figure 2

Figure 2: Line graph

Creating a line graph
Let us look at how to create a simple line graph. Locate the directory where jpgraph.php can be found. Include this file in your code:


Next, in order to draw a line graph, you need to include the jpgraph_line.php file, as follows:


Now, to create a graph, instantiate the Graph class by passing its width and the height, respectively.

$graph = new Graph(300, 400); //300 is the width and 400 is the height
$graph->SetScale(‘intln’); //set the scale of the graph

Prepare the data to be plotted as a line graph using an array:

$data = array(2, 2, 5, 6, 7, 8);

Now create the plot:

$plot = new LinePlot($data);

Add the plot to the graph using the Add function:


Finally, display the graph using the Stroke function:


The graph for the above code is shown in Figure 2.

Figure 3

Figure 3: Bar graph

Creating a bar graph
In order to create a bar graph, include the code from jpgraph.php as well as from jpgraph_bar.php. jpgraph_line.php is not required here.

//create the graph
$graph = new Graph(350,220); //set the width and the height
$graph->SetScale(“textlin”); //set the scale of the graph
$data=array(10,12,30,60); //prepare the data
// Create the bar plots and add it to the graph
$barplot = new BarPlot($data);
$graph->Stroke(); //display the graph

The graph for the above code is shown in Figure 3.
You may use the package to create various other types of graphs as well. Go ahead and explore JpGraph!