Dynamically Creating Graphs and Charts with PHP and GDChart

August 14, 2008

Tutorials

Friday Night Fever

If you’ve been working with PHP for a while, you already know that the language makes dynamic image generation very simple: the GD extension and a few lines of PHP code are all you need to create a JPEG, GIF or PNG image from scratch. However, while this works remarkably well for simple tasks, it can become tedious and complicated if you need to generate more complex images, such as graphs and charts, at run-time.

Take, for example, the task of turning a set of data values into a pie chart image. To arrive at the required result, you would need to allocate colors for each slice of the pie, calculate arc endpoints corresponding to the slice sizes, draw arcs and lines, fill each slice with a different color, write a descriptive text string and percentage value next to each slice, and render the final image. Completing the task might require between 80-100 lines of code and a few hours of debugging time…definitely not the most fun way to spend a Friday evening!

However, there’s a simpler alternative: PHP’s GDChart extension, which provides a full-featured API to efficiently generate charts and graphs. This extension, which is freely available from PECL, can significantly reduce the amount of work involved in dynamically generating graphical representations of numerical data at run-time. Over the next few pages, I’ll introduce you to this extension, illustrating its important features and showing you just how easy it is to get your Friday evening back.

Putting The Pieces Together

GDChart support in PHP comes through PECL’s ext/gdchart extension, which is maintained by Ilia Alshanetsky and Rasmus Lerdorf, and provides an object-oriented API for chart generation. This ext/gdchart extension, in turn, requires you to have GD support compiled into your PHP build. On UNIX systems, this is accomplished by downloading and installing the GD libraries from http://www.boutell.com/gd/ (if you don’t already have them), and then compiling PHP with the –with-gd configuration directive.

Once this is done, you can proceed to install the GDChart extension using the pecl command. Note that at the current time, a Windows version of ext/gdchart is not available; the following steps assume a *NIX system.

shell# pecl install gdchart-beta

The PECL installer will now download the source code, compile it and install it to the appropriate location on your system.

Alternatively, manually download the source code archive (v0.2.0 at this time) from http://pecl.php.net/package/GDChart and compile it into a loadable PHP module with phpize:

shell# cd gdchart-0.2.0
shell# phpize
shell# ./configure
shell# make
shell# make install

This procedure should create a loadable PHP module named gdchart.so in your PHP extension directory. You should now enable the extension in the php.ini configuration file, restart your Web server, and check that the extension is enabled with a quick call to phpinfo():

One important note from the extension’s documentation bears repeating: if you encounter errors related to ‘GDC_title_font’ when compiling the extension, look inside your php_config.h and make sure that it includes a definition for LIBFREETYPE. More detailed instructions for this can be found in the documentation included with the source code.

Rain Dance

Once you’ve got the extension installed and working, it’s time to take it for a test drive. Here’s a simple example, which generates a bar chart for annual rainfall data:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// generate PNG chart and send to client
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

This script begins by creating a new instance of the GDChart class and passing the constructor a constant indicating the type of chart (in this case, a bar chart). Next, the instance’s addValues() method is used to add data points to the chart (as an array), while the setLabels() method is used to set corresponding X-axis labels. Once all these preliminaries have been taken care of, the instance’s out() method takes care of actually preparing and rendering the chart.

The parameters passed to out() include the height and width of the output image, the image format (GIF, JPEG, WBMP or PNG), and an optional filename for the chart. In this case, because the output image is sent directly to the client, no filename is needed.

Here’s what the output looks like:

GDChart supports 20 different chart formats, so it’s pretty easy to represent the same data as, say, a line graph, by merely changing the value passed to the constructor:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::LINE);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

And here’s what the revised output looks like:

Prefer an area chart? No problem:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::AREA);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

And here’s the output:

Notice that in all these cases, changing the chart type was as simple as passing the object constructor a different argument; the main body of the script remained unchanged. If, on the other hand, you were creating the chart “by hand” using GD functions, it would be a lot of work to switch from one chart type to another. Thus, ext/gdchart offers significant efficiency benefits for dynamic chart generation.

While you’re chewing on that, here’s a complete list of the different chart types supported by ext/gdchart:

Constant Chart Type
LINE Line
BAR Bar
AREA Area
FLOATINGBAR Floating Bar
HILOCLOSE High/Low/Close (HLC)
COMBO_LINE_BAR Combination Line and Bar
COMBO_HLC_BAR Combination HLC and Bar
COMBO_LINE_AREA Combination Line and Area
COMBO_LINE_LINE Combination Line and Line
COMBO_HLC_AREA Combination HLC and Area
PIE_2D 2D Pie
PIE_3D 3D Pie
BAR_3D 3D Bar
AREA_3D 3D Area
LINE_3D 3D Line
HILOCLOSE_3D 3D HLC
COMBO_LINE_BAR_3D 3D Combination Line and Bar
COMBO_LINE_AREA_3D 3D Combination Line and Area
COMBO_LINE_LINE_3D 3D Combination Line and Line
COMBO_HLC_BAR_3D 3D Combination HLC and Bar
COMBO_HLC_AREA_3D 3D Combination HLC and Area
FLOATINGBAR_3D 3D Floating Bar

Stack Me Up

To compare one data set with another, simply call the addValues() method again with a different set of values. GDChart will automatically create a new plot for you, making comparative analysis easy. To illustrate, here’s an example of two data sets in the same line graph:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::LINE);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));
$gdc->addValues(array(8234, 6484, 6574, 7464, 10474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

Here’s the output:

With the ‘stackType’ property, you can even stack data sets together in the same chart. Here’s an example of a bar chart, with the bars stacked besides each other:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));
$gdc->addValues(array(8234, 6484, 6574, 7464, 10474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// set stacking
$gdc->stackType=GDChart::STACK_BESIDE;

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

Here’s the output:

Alternatively, set the ‘stackType’ property to STACK_LAYER, to generate a chart with the bars stacked inside each other:

You can also add X- and Y- axis labels, as well as a title for the chart. Here’s an example:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// set titles
$gdc->title = 'ANNUAL RAINFALL';
$gdc->xtitle = 'MM';
$gdc->ytitle = 'YEAR';

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

And here’s the output:

An Eye For Color

Adjusting chart colors is accomplished through the careful use of the GDChart object’s setColors() method and ‘bgColor’, ‘gridColor’ and ‘lineColor’ properties. The setColors() method accepts an array of colors (in hexadecimal notation) for the graph itself, while the ‘bgColor’, ‘gridColor’ and ‘lineColor’ properties control, respectively, the color of the chart background, the color of the grid and the color of the gridlines. Here’s an example illustrating these properties and methods in action:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// set titles
$gdc->title = 'ANNUAL RAINFALL';
$gdc->xtitle = 'MM';
$gdc->ytitle = 'YEAR';

// set colors
$gdc->setColors(array(0x0000a0));
$gdc->bgColor = 0xffffff;
$gdc->gridColor = 0xff0080;
$gdc->lineColor = 0xff0080;

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

This example sets the chart background color to white, the bars to blue and the gridlines to pink. Flashy? Maybe, maybe not…here’s the result:

If you like, you can give each bar of a bar chart a different color, with the setExtColors() method. Here’s an example:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// set titles
$gdc->title = 'ANNUAL RAINFALL';
$gdc->xtitle = 'MM';
$gdc->ytitle = 'YEAR';

// set colors for individual bars
$gdc->setExtColors(array(0x00ff00,0x0000ff,0xff0000,0xffff00,0xff00ff));

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

And here’s the output:

It’s also possible to customize the colors of the X- and Y-axis labels and titles, the chart title, and the chart grid and borders. The following listing illustrates:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// set titles
$gdc->title = 'ANNUAL RAINFALL';
$gdc->xtitle = 'MM';
$gdc->ytitle = 'YEAR';

// set colors
$gdc->setColors(array(0x0000a0));
$gdc->titleColor = 0x00ffff;
$gdc->xtitleColor = 0xff0000;
$gdc->ytitleColor = 0x00ff00;
$gdc->xlabelColor = 0xff0000;
$gdc->ylabelColor = 0x00ff00;

// set grid and borders
$gdc->grid = 0;
$gdc->zeroShelf = 1;
$gdc->border = GDChart::BORDER_Y;

// generate image
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

The ‘titleColor’, ‘xtitleColor’, ‘ytitleColor’, ‘xlabelColor’ and ‘ylabelColor’ properties should be self-explanatory, but the ‘grid’, ‘zeroShelf’ and ‘border’ properties require a little more explanation. The ‘grid’ property controls the chart’s background grid, while the ‘zeroShelf’ property indicates whether or not the horizontal X-axis should be displayed. The ‘border’ property controls the chart border, and can accept any of the values BORDER_NONE, BORDER_ALL, BORDER_X, BORDER_Y, BORDER_Y2 or BORDER_TOP. Here’s the result:

The ‘titleSize’, ‘xtitleSize’ and ‘ytitleSize’ properties allow you to control the size of the chart title, X-axis title and Y-axis title respectively; these may be set to any of the self-explanatory values FONT_TINY, FONT_SMALL, FONT_MEDBOLD, FONT_LARGE or FONT_GIANT. Similarly, the ‘barWidth’ property allows precise control over the width of each bar in a bar chart. Here’s an example of these properties in action:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// set titles
$gdc->title = 'ANNUAL RAINFALL';
$gdc->xtitle = 'MM';
$gdc->ytitle = 'YEAR';

// set colors
$gdc->setColors(array(0x0000a0));
$gdc->titleColor = 0x00ffff;
$gdc->xtitleColor = 0xff0000;
$gdc->ytitleColor = 0x00ff00;
$gdc->xlabelColor = 0xff0000;
$gdc->ylabelColor = 0x00ff00;

// set bar width and title sizes
$gdc->barWidth = 50;
$gdc->xtitleSize = GDChart::FONT_LARGE;
$gdc->ytitleSize = GDChart::FONT_LARGE;

// generate image
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

And here’s the output:

Finally, the ‘bgImage’ property allows you to place a GIF image as the background for your chart. Here’s an example:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues(array(18234, 16484, 16574, 17464, 19474));

// add X-axis labels
$gdc->setLabels(array('2002', '2003', '2004', '2005', '2006'));

// set titles
$gdc->title = 'ANNUAL RAINFALL';
$gdc->xtitle = 'MM';
$gdc->ytitle = 'YEAR';

// set colors
$gdc->setColors(array(0x0000a0));
$gdc->titleColor = 0x00ffff;
$gdc->xtitleColor = 0xff0000;
$gdc->ytitleColor = 0x00ff00;
$gdc->xlabelColor = 0xff0000;
$gdc->ylabelColor = 0x00ff00;

// set chart background image
$gdc->bgImage = 'logo.gif';

// generate image
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

And here’s the output:

Not My Type

Now that you know how to make your charts look pretty, let’s talk a little bit more about the different types of charts supported by ext/gdchart. In addition to the standard bar and line charts, you’ve seen so far, ext/gdchart also supports scatter plots, high/low/close graphs and pie charts.

Let’s look at scatter plots first. Here’s a simple example:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::LINE);

// set data values
$gdc->addValues(array(null, 7, 6, 9));

// add scatter points
$gdc->addScatter(8, 1, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(10, 1, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(5, 1, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(5, 1, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(6, 2, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(11, 2, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(3, 2, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(4, 2, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(10, 3, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(12, 3, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(3, 3, GDChart::SCATTER_CIRCLE, 0xff0000, 5);
$gdc->addScatter(11, 3, GDChart::SCATTER_CIRCLE, 0xff0000, 5);

// set labels, colors and borders
$gdc->setLabels(array(null, 'A', 'B', 'C'));
$gdc->setColors(array(0x0000ff));
$gdc->grid = 0;
$gdc->border = GDChart::BORDER_Y;
$gdc->zeroShelf = 1;

// generate image
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

Here’s the output:

The only unfamiliar thing in this script is the addScatter() method. This method accepts five parameters: a point value, a position, a constant indicating the symbol to use for the point marker, a hexadecimal color code, and a size value. These parameters are then used to plot the corresponding point on the chart. You can call addScatter() as many times as you need for a single chart.

How about a high/low/close chart then? Here’s how to create one:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::HILOCLOSE);

// set 'high' data set
$gdc->addValues(array(5,6,7,9));

// set 'low' data set
$gdc->addValues(array(1,2,3,4));

// set 'close' data set
$gdc->addValues(array(4,5,2,7));

// set labels, colors and styles
$gdc->setLabels(array('2002', '2003', '2004', '2005'));
$gdc->setColors(array(0x00ff00,0xff0000,0x0000ff));
$gdc->hlcStyle = GDChart::HLC_DIAMOND;

// generate image
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

Here’s what the output looks like:

In this chart type, three different data sets – one each for high, low and close – are attached to the chart by repeatedly calling the addValues() method. The ‘hlcStyle’ property is used to control the appearance of the ‘close’ marker, and can take any one of the values HLC_DIAMOND, HLC_CLOSE_CONNECTED, HLC_CONNECTING or HLC_I_CAP. Play with these a little to see what each one does.

Pie In The Sky

Pie charts are extremely popular, and so it’s no surprise that GDChart comes with various properties and methods specifically for these types of charts. First up, the basic pie chart:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::PIE_3D);

// set pie slices and labels
$gdc->addValues(array(50, 30, 100, 20));
$gdc->setLabels(array('UK', 'US', 'Europe', 'India'));

// set chart title
$gdc->title = 'ANNUAL SALES BY LOCATION';

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

A pie chart is created in the same manner as other types of charts: initialize a GDChart object with the chart type, attach values and descriptive labels to the pie slices with the addValues() and setLabels() methods, and render the chart with out(). Here’s the result:

A nice touch would be to display the percentage of the pie occupied by each slice. With GDChart, this is a snap (and hey, it even calculates the percentages for you!):

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::PIE_3D);

// set pie slices and labels
$gdc->addValues(array(50, 30, 100, 20));
$gdc->setLabels(array('UK', 'US', 'Europe', 'India'));

// set chart title
$gdc->title = 'ANNUAL SALES BY LOCATION';

// format labels
$gdc->percentLabels = GDChart::LABEL_ABOVE;
$gdc->percentFmt = '%0.2f%%';

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

Here, the ‘percentLabels’ property tells GDChart where to display the percentage value relative to each slice’s label (above, below, left or right), while the ‘percentFmt’ property lets you apply printf()-style formatting to the percentage display. Here’s the result:

Why stop there? GDChart also lets you customize the color of each slice and slice label, and even “explode” one or more slices for greater visual effect. Take a look:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::PIE_3D);

// add pie values and labels
$gdc->addValues(array(50, 30, 100, 20));
$gdc->setLabels(array('UK', 'US', 'Europe', 'India'));

// set chart title
$gdc->title = 'ANNUAL SALES BY LOCATION';

// set colors
$gdc->setColors(array(0xff0000,0x00ff00,0x0000ff,0xffff00));
$gdc->edgeColor = 0xff00ff;

// set exploded slice
$gdc->setExplode(array(30,0,0,0));

// format labels
$gdc->labelLine = true;
$gdc->labelDist = 25;
$gdc->labelSize = GDChart::FONT_SMALL;
$gdc->percentLabels = GDChart::LABEL_ABOVE;
$gdc->percentFmt = '%0.2f%%';

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

As before, the setColors() method accepts an array of color codes (in hexadecimal notation) corresponding to the array of data values, and sets each slice to the corresponding color. The edges of each slice can be further outlined in a different color with the ‘edgeColor’ attribute, which is similar to the ‘lineColor’ attribute seen in earlier examples.

The labels that appear next to each pie slice may also be customized via the ‘labelLine’, ‘labelDist’ and ‘labelSize’ properties. The ‘labelLine’ property accepts a Boolean value indicating whether each pie slice should be linked with its descriptive label with a short line pointer, while the ‘labelDist’ property defines the distance between a pie slice and its corresponding label. The size of each label may be further adjusted with the ‘labelSize’ property, which accepts any one of the five pre-defined font sizes discussed earlier.

It’s also possible to detach one or more slices of the pie and “explode” it outwards for emphasis, with the setExplode() method. This method accepts an array of values corresponding to the array of data values, with each value representing the distance of the corresponding pie slice from the center; the higher the value, the greater that slice’s distance from the center. In the previous example, the slice representing the UK has been “exploded” outwards, to display the following result:

Finally, no discussion of GDChart’s pie charts would be complete without a mention of the setMissing() method, which lets you “hide” one or more slices of the pie. This method accepts an array of Boolean values corresponding to the array of data values, and hides those slices flagged as Boolean true. Here’s an example, which hides the slice for India:

<?PHP
// initialize object with chart type
$gdc = new GDChart(GDChart::PIE_3D);

// add pie values and labels
$gdc->addValues(array(25, 15, 50, 10));
$gdc->setLabels(array('UK', 'US', 'Europe', 'India'));

// set chart title
$gdc->title = 'ANNUAL SALES BY LOCATION';

// set colors
$gdc->setColors(array(0xff0000,0x00ff00,0x0000ff,0xffff00));
$gdc->edgeColor = 0xff00ff;

// set hidden slice
$gdc->setMissing(array(FALSE,FALSE,FALSE,TRUE));

// format labels
$gdc->labelLine = true;
$gdc->labelDist = 25;
$gdc->labelSize = GDChart::FONT_SMALL;
$gdc->percentLabels = GDChart::LABEL_ABOVE;
$gdc->percentFmt = '%0.2f%%';

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

And here’s the result:

Searching For Answers

Now that you’ve seen what the GDChart extension can do, let’s wrap this up with a practical example. Assume for a moment that you have a reasonably popular Web site with lots of interesting articles and tutorials, and that you’ve got a little bit of PHP code that’s diligently logging the searches performed by users on your site to a database. Assume further that the database table to which these queries are being logged looks like this:

mysql> DESC searchlog;
+---------------+-----------+------+-----+-
| Field         | Type      | Null | Key |
+---------------+-----------+------+-----+-
| id            | int(10)   | NO   | PRI |
| qry_str       | text      | NO   |     |
| qry_time      | timestamp | YES  |     |
| qry_num_rslts | int(10)   | NO   |     |
+---------------+-----------+------+-----+-
4 rows in set (0.04 sec)

Now, wouldn’t it be nice to see all this search log data neatly summarized by day in a graph? Of course it would…and with ext/gdchart, it’s a snap to do! Here’s the code:

<?PHP
// connect to MySQL
$mysqli = new mysqli("localhost", "user", "pass", "db");
if ($mysqli === false) {
  die("ERROR: Could not connect. " . mysqli_connect_error());
}

// execute query
// get count of records for each day of current monts
$sql = "SELECT COUNT(*) AS count, DATE_FORMAT(qry_time, '%d-%m-%y') AS date FROM searchlog WHERE MONTH(qry_time) = MONTH(NOW()) GROUP BY DATE_FORMAT(qry_time, '%d-%m-%y')";
$result = $mysqli->query($sql);
$data = array();
while($row = $result->fetch_object()) {
  $data['values'][] = $row->count;
  $data['labels'][] = $row->date;
}
$result->close();

// close connection
$mysqli->close();

// initialize object with chart type
$gdc = new GDChart(GDChart::BAR);

// add data points
$gdc->addValues($data['values']);

// add X-axis labels
$gdc->setLabels($data['labels']);

// set titles
$gdc->title = 'QUERIES PER DAY';
$gdc->xtitle = 'DATE';
$gdc->ytitle = 'COUNT';

// generate chart
header('Content-Type:image/png');
echo $gdc->out(300,200,GDChart::PNG);
?>

Nothing too complex here – the script connects to the MySQL database, executes a GROUP BY query that essentially returns a count of the number of search queries executed in each day of the current month, and turns the result into an array. This array is then passed to the GDChart object’s addValues() and setLabels() methods, and used to generate a neat bar graph of the number of queries per day.

Here’s a sample of the output:

As these examples illustrate, the GDChart extension provides a way to quickly and efficiently turn numerical data into easy-on-the-eyes graphs and charts. Take a look at it the next time you have a chart to generate…and happy charting!

This article copyright Melonfire, 2008. All rights reserved.

7 Responses to “Dynamically Creating Graphs and Charts with PHP and GDChart”

  1. _____anonymous_____ Says:

    installed gd and gdchart. seemed to work out just fine.

    however, $gdc->out gives me nothing at all. the script just returns a completely empty response.

    any help would be greatly appreciated!

  2. _____anonymous_____ Says:

    Hi,

    I am using gdchart on Fedora Core 8 with PHP 5.2.6. I think I am having a similar problem to asood00 because I cannot get the bar charts to display properly. Instead of showing a bar I get a red line. Does anyone have any comments or suggestions of what to do. Thanks a lot.

  3. _____anonymous_____ Says:

    This is a really good article but I’d love to learn the other options. I’ve spent ages Googling but come up with nothing…

    Can anyone point me in the right direction?

  4. _____anonymous_____ Says:

    good read, im growing tired of these heavy interactive client side charting solutions with flash/js/canvas/whatever when all I need is a plain ol’ gif ;)

  5. asood00 Says:

    I am using PHP5 bundled gdlib along with gdchart extension. I have tried these code snippet. I can draw all the charts except the bar chart. When I select bar chart, it displays everything but the bars itself. I even have tried changing the bar width but no use.

  6. rizwan6feb Says:

    Here is also a nice tutorial on creating bar graphs in php
    http://www.qualitycodes.com/tutorial.php?articleid=20

  7. _____anonymous_____ Says:

    Is it possible to set values (scale) on the Y-Axis?