Very Basic Pie Chart

Published: December 30th, 2008 by:

Pie chart, circle graph, call it what you want, but these charts are loved by descriptive statisticians across the world for their instant appeal to the viewer's eyes and inferential mind.  Though descriptive statistics can be deceiving, pie charts, created in this article with the GD library, easily describe the data in a very literal way.  In this post, we'll go over the basic GD functions available for putting together a simple pie chart.


So far in the GD library series, I’ve detailed several key functions that one should certainly know before diving in to an extensive project.  To review some of these functions as involved with an application, check out the series thus far.

Now that you know about declaring colors, fonts, and setting up the basics of the image, let’s get right to revealing the newest (and only new) function in this article, imagefilledarc(), declared like this:


<?php

...

imagefilledarc($img,$cX,$cY,$width,$height,$startDeg,$endDeg,$col,$style);

...

?>

Now, let’s break this down, as this is quite a hefty function:

  • $img = The image you are working with, established with something like imagecreate()
  • $cX, $cY = The coordinates of the pixel that will be the center of the arc, and in this case, the entire pie chart
  • $width, $height = Quite obviously, the width and height of the arc, meaning the pixel span horizontally and then vertically
  • $startDeg, $endDeg = The starting and ending point on the circle for the arc, in degrees
  • $col = The color to fill the arc with, as established earlier with imagecolorallocate()
  • $style = One of several styles available, including IMG_ARC_PIE, IMG_ARC_CHORD, IMG_ARC_NOFILL, IMG_ARC_EDGED, and in this article we’ll be focusing on IMG_ARC_PIE

With this basic understanding of the function, let’s put together a basic pie chart with everything we know.  We’ll begin, as we typically do, by establishing the image and creating a blank, white canvas to work with.


<?php

$pie = imagecreate(500,500);

$white = imagecolorallocate($pie,255,255,255);

imagefill($pie,0,0,$white);

...

?>

Obviously, if you were putting together an accurate pie chart, you would have actual data and statistics to work with, but in this case, we’re just running through the basics, so we’ll use rather even, easy percentages.  Next, we’ll create an array holding the five percentages that will define the five “slices” of the pie, and we’ll also load a font to use later with labeling.  You remember how to load a font, right?


<?php

...

$font = imageloadfont('arial.gdf');

$black = imagecolorallocate($pie,0,0,0);  //This is for the labeling also

$percentages = array("40","30","15","10","5");

...

?>

Next, we’ll put together that awesome pie (I understand if you’re starting to get hungry), and I like to use a simple for() loop.  Either you can manually set the loop values if you know how many values you will have at all times, or you can make it a bit more dynamic, letting PHP do the calculations.  Let’s do this slowly, simply setting up the loop and the calculations.


<?php

...

$x = 0;

for ($z=0, $c=count($percentages); $z<$c; $z++) {

$degrees = (($percentages[$z]/100)*360);

$color = imagecolorallocate($pie,mt_rand(20,255),mt_rand(20,255),mt_rand(20,255));

...

?>

With just this, we are ready to create the “slices” of the pie, but I want to be sure a couple of things about the loop are made clear.  First of all, if you are going to use the count() function to set the limit, establish it with the incrementing variable; otherwise, PHP will have to calculate it each time the loop is run through which demands more time and resources.  Also, make sure you understand the reason for the variable before the loop. With this, we establish ‘x’ as the starting degree and set it to ‘0,’ as that is where we want to start.  When calculating the degrees for each element, you can actually just multiply the percentage by 3.6, but I wanted to be sure it was obvious what I was doing there.  Lastly, we dynamically set a color, as we want each “slice” to be different.  In reality, we could end up with two slices of the same color, but the chances are slim.  Feel free to take the necessary precautions to prevent this, if you wish.  Now, let’s get to the most important part, making, not baking, a pie:


<?php

...

$x = 0;

for ($z=0, $c=count($percentages); $z<$c; $z++) {

$degrees = (($percentages[$z]/100)*360);

$color = imagecolorallocate($pie,mt_rand(20,255),mt_rand(20,255),mt_rand(20,255));

imagefilledarc($pie,100,100,125,125,$x,($x+$degrees),$color,IMG_ARC_PIE);

imagefilledrectangle($pie,250,(50+(25*($z+1))),275,(75+(25*($z+1))),$color);

imagestring($pie,$font,276,(55+(25*($z+1))),$vals[$z]."%",$black);

$x+=$degrees;

}

header("Content-type: image/png");

imagepng($pie);

imagedestroy($pie);

?>

Finally, we have our pie chart.  We simply use the calculations we already found, along with whatever center, width, and height you wish to use to draw the pie.  Then, we simply label the pie with the corresponding percentages.  With a more complex script, you could easily label the pie with the actual descriptors for each “slice.”  Finally, we add on the total degrees to reset the starting value for the next section.  Then, output the image and your pie is ready to eat, or rather, look at.

I want to stress with this script that I titled it quite appropriately; this is a basic pie chart.  There are definitely ways to make it look more appealing, certainly, but with this basic setup, you are on your way to becoming a professional statistician, except for all that fancy math behind it.

Check out a sample pie chart; enter a list of percentages (that must add up to 100; there is nothing in place to check for this) and watch your pie come to life.


Leave a Reply





Wordpress doesn't like it when you post PHP code. Go save your code at pastebin, and post the link here.

About the Author

Kurtis has been working with PHP for nearly four years, and he has moderate experience with MySQL as well as other programming languages, like Java and C++.