In this example, we go over usage of the PHPGraphLibPie extension, used to make pie charts. Before you read this example, make sure you are familiar with usage of the regular PHPGraphLib class. Tutorial #1 is a good place to start.
Include both the PHPGraphLib and PHPGraphLibPie class files at the top of your stand alone php script. This script will only include the PHP calls to create your pie chart. Next, create a PHPGraphLibPie object.
<?php include("phpgraphlib.php"); include("phpgraphlib_pie.php");
Next, you have to create a PHPGraphLibPie object. You may leave the arguments blank to use default dimensions, or you may specify your own width and height.
$graph = new PHPGraphLibPie(450,280);
Just like the regular PHPGraphLib class, you must call the addData() function on your PHPGraphLibPie 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("Direct Sales"=>150000, "Renewels"=>258000, "Internet Orders"=>65000, "Wholesale"=>450000); $graph->addData($data);
In a dynamic web application environment, you could query a database and pass an array of values into your PHPGraphLibPie object.
In this example we have decided to give the graph a title and change the displayed % labels from their default, which is black, to blue.
$graph->setTitle("Department Sales Comparison"); $graph->setLabelTextColor("blue");
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.
Here is the whole script we created above:
<?php include("phpgraphlib.php"); include("phpgraphlib_pie.php"); $graph=new PHPGraphLibPie(450,280); $data=array( "Direct Sales"=>150000, "Internet Orders"=>65000,"Renewels"=>258000, "Wholesale"=>450000); $graph->addData($data); $graph->setTitle("Department Sales Comparison"); $graph->setLabelTextColor("blue"); $graph->createGraph(); ?>
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="pie_chart.php" /> </html>
You're done! Here is the pie chart you just created:
For other examples, view the Examples page