PHPBuilder - Bar Charts With GD



RSS Twitter
Articles Php Functions

Bar Charts With GD

by: Stefan Wiesendanger
|
December 17, 2000

Introduction

In this tutorial, I will give ideas on how the graphics capabilities of PHP can be used to create simple bar charts in GIF and PNG format. I will briefly touch on non-graphics alternatives as well. My objective is to show you some basics that will enable you to proceed to much more complex charts. The included code will give you a working foundation to start with. If you are looking for further inspiration after this tutorial, you can find pointers to related code - most notably for pie charts - in the very end.
The focus will be on drawing. We'll create a chart from an array $data whose keys will be taken to be the X axis labels and whose values are the numbers to be plotted on the Y axis. I will not address the question of how to get data into the array in the first place. If you are interested in that information, I recommend you read the column "Graphing With PHP and GD" by Allan Kent here on PHPBuilder.
One of the neat features of PHP is that you can create graphics on the fly. In order to accomplish this, you need to compile PHP with the GD image library or install it from packages that support GD. Under Linux, the standard mod_php3 RPM packages from RedHat have everything you'll need for running PHP3 as an Apache module. If you insist on the newer PHP4, RPMs are available from Troels Arvin at http://fsr.ku.dk/people/troels/rpms/php/. Before long, more official versions should also show up on RPMfind and other redhat-contrib mirrors.
To integrate a PHP generated image into your web pages, all it takes is an HTML IMG tag which will call a script that streams image data to the browser, instead of the IMG tag pointing to a file on disk:
<IMG SRC="chart.php" HEIGHT="height_of_chart" WIDTH="width_of_chart">
I have used the techniques described on several production sites for over a year without any problems. Just one word of caution: if you put dynamically generated graphics on all your pages, performance may suffer. But don't despair, I'll describe several cures for this problem later.
In general, I like to stick to the "keep it simple" rule. That's why I am going to cover some alternative ways for drawing charts before entering into the subject of how to create pixel graphics. For your needs, it may not even take all the layout control and flexibility of a bitmapped image.

1
|
2
|
3
|
4
|
5
|
6
|
7
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Stefan Wiesendanger

Comment:



Comment:

(Maximum characters: 1200). You have characters left.