View Single Post
Old 12-13-2008, 10:11 PM   #1 (permalink)
Rendair
The Addict
Upcoming Programmer Top Contributor 
 
Rendair's Avatar
 
Join Date: Nov 2007
Location: UK
Posts: 319
Thanks: 18
Rendair is on a distinguished road
Default Pie Charts In PHP

Ok well Orc i believe wanted a pie chart tutorial. SO here i go,

http://www.jooney.co.uk/php/piechart/pieChart/pie.php

You can see the example above. It automatically adds pieces to the pie depending on how many items there are in an array and of course made it abit more interesting in having randomly changing slices :)

first things first lets define the header information

PHP Code:
header ("Content-type: image/pjpeg"); //define the page to be a image 
Ok now we can create the array.

PHP Code:
$array = array(9885,2350,5775,9228,7800,2689,9889,10000);
$total array_sum($array);
sort($array);
$counter 0
Now we need to work out some values that will be used in the pie of course the chart has to equal 360 and no more.

PHP Code:
foreach($array as $value)
{
      
$result[$counter] =  round($value $total 360,0);
      
$counter++;

Its kind of up to you if you wish to round the numbers or not.

Now lets create the image

PHP Code:
$im imagecreate(500,600);
imagecolorallocate ($im0,12,225); 
Ok now its time to go through and make the pieces of the pie....wow that sounds good doesnt it. lol

PHP Code:
$i count($array)-1;
$prevTotal 360;
foreach(
$result as $value)
{
        
$rand1 rand(0,255);
        
$rand2 rand(0,255);
        
$rand3 rand(0,255);
        
$colour imagecolorallocate ($im$rand1,$rand2,$rand3);

        
imagefilledarc ($im250230,400,400,0,$prevTotal,$colourIMG_ARC_PIE);
        
$i--;
        
$prevTotal $prevTotal $result[$i];

You maybe wondering why i used a for each loop, but i couldnt be bothered to use a for loop lol you can do so if you wish, but as long as you get the idea then its all good.

Now the rest is up to use its a very basic way of showing the values of the data. The way i did it was to make it so it didnt make the values appear off the bottom.

PHP Code:
    $rand1 rand(0,255);
    
$rand2 rand(0,255);
    
$rand3 rand(0,255);

    
$j count($array)-1;
    
$start 500 count($array) * 10;
    
$add 0;

    foreach(
$array as $value)
    {
        
imagestring($im,2,10,$start+$add,$value,$colour);
        
$j--;
        
$add += 10;
    }
    
//Add the text
    
imagestring($im,5,10,580," Coded By: Dale ( Rendair )",$colour);


    
imagejpeg ($im); 
and thats it...very simple id say...if you want anymore detail let me know....when i have time ill try make it better, but im sure from what is here you can work out ways of making it abit better. It gets the job done.
__________________
www.jooney.co.uk - the online portfolio
Send a message via MSN to Rendair
Rendair is offline  
Reply With Quote
The Following User Says Thank You to Rendair For This Useful Post:
Orc (12-14-2008)