Jump to content

How to Generate Charts with JPGraph and PHP

0
  adfm's Photo
Posted May 14 2010 11:39 AM

If you need to plot some report data on-the-fly, then look no further than JPGraph. This excerpt from Peter MacIntyre's PHP: The Good Parts will introduce you to JPGraph and get you building pie charts, bar charts and even captcha images in no time. The examples assume a basic knowledge of PHP.


JPGraph is used to make graphical statistical reports like bar charts and pie charts. It is an object-oriented code library, so by now it should be fairly straightforward for you to use. As before, you access this library with a require statement.

Typically, a graphical report will ask the user for input in order to build the report. This is information like the date range that the report will cover, the sorting order of the data, and so on. In our samples, however, we will simply provide arrays with preset values to make them a little easier to review.

Pie Charts

The first sample graph that we will look at is a pie chart. In the following listing you will see an array of data to be plotted on the chart assigned to a variable called $data; this is the data that would normally be provided by a data entry page, a select statement from a database, or a combination of both. We can do this after we bring in the appropriate libraries for the chart that we are about to build.

JPGraph is a little different than other libraries in the sense that there is a basic library required by all graphs being generated, as well as individual specialized libraries, or sublibraries, that are more suited to each graph type. In this case, we use the jpgraph_pie.php file because we are creating a pie chart. After we reference the correct libraries and provide the raw data, we instantiate the $piechart class from the PieGraph object and pass two numbers representing the width and height of the chart to the constructor. Then we simply start using the methods available to us to build the chart.

We can control the look of the title of the chart by setting the title text, its font, and its colors. Then we instantiate an object called $pPlot, which is a rendition of the pie shape itself and how it is sliced up based on the $data array we built earlier. Next, we can describe the labels that will accompany each slice of the pie. Finally, we add the plotted chart onto the graph with the Add method, and display the whole thing with the Stroke method:

include ("../../jpgraph/jpgraph.php");

include ("../../jpgraph/jpgraph_pie.php");



$data = array(12, 15, 23, 18, 5);



// Create the Pie Graph.

$piechart = new PieGraph(300,350);



// Set a title for the plot

$piechart->title->Set("Sample Pie Chart");

$piechart->title->SetFont(FF_VERDANA,FS_BOLD,12);

$piechart->title->SetColor("darkblue");

$piechart->legend->Pos(0.1,0.2);



// Create pie plot

$pPlot = new PiePlot($data);

$pPlot->SetCenter(0.5,0.55);

$pPlot->SetSize(0.3);



// Setup the labels

$pPlot->SetLabelType(PIE_VALUE_PER);

$pPlot->value->Show();

$pPlot->value->SetFont(FF_ARIAL,FS_NORMAL,9);

$pPlot->value->SetFormat('%2.1f%%');



// Add and stroke

$piechart->Add($pPlot);

$piechart->Stroke();

Note

The time function is added here to trigger a difference in the browser’s cache registration so that the same file can be used by many concurrent users of the same web page.

This code will send the graph shown in Figure 8.12 to the browser. Remember that you can augment this display with other HTML markup if desired.

Figure 8.12. Pie chart generated by JPGraph and PHP

Attached Image

Note

If you decide to add additional formatting to the output of the graph, you will have to save the generated graphic as a file and pivot it to the server’s hard drive for later display with the accompanying HTML. The stroke method used to generate the graph has an option to name the file and save it for you. The code to save the graphic is:

$graph->Stroke("graph.jpg");

And the code to bring the graphic back to combine with HTML code is:

echo ('<img src="graph.jpg?' .time(). '">');

Bar Charts

Another type of chart that we can create is a bar chart. Again, here we will provide the benchmark values to the graph directly for easier code review. The code for this sample follows, and you will see that it uses the specific sublibrary for bar charts to work properly. Other than the proper selection of the sublibrary, there is really not too much difference in the approach—there are specific methods used, but the concept is basically the same. Here is the code:

include ("&#46;&#46;/&#46;&#46;/jpgraph/jpgraph.php");

include ("&#46;&#46;/&#46;&#46;/jpgraph/jpgraph_bar.php");

include ("&#46;&#46;/&#46;&#46;/jpgraph/jpgraph_line.php");



// We need some data

$datay=array(31,44,49,40,24,47,12);



// Set up the graph

$graph = new Graph(600,300,"auto");

$graph->img->SetMargin(60,30,30,40);

$graph->SetScale("textlin");

$graph->SetMarginColor("teal");

$graph->SetShadow();



// Create the bar pot

$bplot = new BarPlot($datay);

$bplot->SetWidth(0.6);



// Set up color for gradient fill style

$tcol=array(100,100,255);

$fcol=array(255,100,100);

$bplot->SetFillGradient($fcol,$tcol,GRAD_VERT);

$bplot->SetFillColor("orange");

$graph->Add($bplot);



// Set up the title for the graph

$graph->title->Set("Sample Bargraph");

$graph->title->SetColor("yellow");

$graph->title->SetFont(FF_VERDANA,FS_BOLD,12);



// Set up color for axis and labels

$graph->xaxis->SetColor("black","white");

$graph->yaxis->SetColor("black","white");



// Set up font for axis

$graph->xaxis->SetFont(FF_VERDANA,FS_NORMAL,10);

$graph->yaxis->SetFont(FF_VERDANA,FS_NORMAL,10);

$graph->yaxis->title->Set("Value Range");

$graph->yaxis->title->SetColor("white");

$graph->yaxis->title->SetFont(FF_VERDANA,FS_NORMAL,10);



// Set up X-axis title (color &amp; font)

$graph->xaxis->title->Set("item Count");

$graph->xaxis->title->SetColor("white");

$graph->xaxis->title->SetFont(FF_VERDANA,FS_NORMAL,10);



// Finally send the graph to the browser

$graph->Stroke();

Figure 8.13 shows the chart that this code produces.

Figure 8.13. Bar chart generated by JPGraph and PHP

Attached Image

Captchas

One last quick sample is in order. If you have ever ordered concert tickets online, you will be familiar with the kind of antispam image shown in Figure 8.14.

Figure 8.14. Antispam graphic generated by JPGraph and PHP

Attached Image

JPGraph can generate this kind of captcha in just a few lines of code, and the supplied characters can be either provided manually (by you) or generated randomly:

require_once "&#46;&#46;/&#46;&#46;/jpgraph/jpgraph_antispam.php";



$spam = new AntiSpam();

// saved to $chars for later verification of correct entry

$chars = $spam->Rand(8);

$spam->Stroke() ;

Be sure to visit the website for this library and review all the other options that it provides. You can add background images to the graphs, adjust the grid lines behind the bars, and so much more. Many other types of charts and graphs are also available, like stock, radar, scatter, polar, and Gantt charts.

PHP: The Good Parts

Learn more about this topic from PHP: The Good Parts.

Get past all the hype about PHP and dig into the real power of the language. This book explores the most useful features of PHP and how they can speed up the web development process, and explains why the most commonly used PHP elements are often misused or misapplied. You'll learn which parts add strength to object-oriented programming, and how to use certain features to integrate your application with databases.

See what you'll learn


Tags:
0 Subscribe


0 Replies