PHP GD Bar Chart
Create Bar chart with PHP and GD
Its very easy i will show you in few steps
You must have installed GD and enable it
Firstly we are going to set a header type as image
header("Content-type: image/jpeg");
Now we are going to set some values in an array to use and then all them all together
$data = array('3400','2570','245','473','1000','3456','780');
$sum = array_sum($data);
Now we need to set the height and width of the actual chart itself.
$height = 230;
$width = 320;
For the sake of this tutorial do not edit this. Otherwise this may cause errors.
Now we can create the actual chart background or where the chart is actually shown on. However you
want to look at it.
$im = imagecreate($width,$height); // width , height px
Now we can set the background colour of the graph and also create some colours we are going to use for
the bars and the lines.
$white = imagecolorallocate($im,255,255,255);
$black = imagecolorallocate($im,0,0,0);
$red = imagecolorallocate($im,255,0,0);
Now its time to create the X & Y axis lines.
imageline($im, 10, 5, 10, 230, $black );
imageline($im, 10, 230, 300, 230, $black);
imageline ( resource image,x-coordinate first point,y-coordinate first point,x-coordinate second point,y-coordinate second point,colour )
Now we need to set up some information so we can place these bars.
$x = 15; // set how far from the side then how far from next bar
$y = 230; // set where bar should reach on the y in this case on the y line we created
$x_width = 20; // Width of each of the bars
$y_ht = 0; //height of the bars
Now we can start creating the bars themself.
for ($i=0;$i<7;$i++)
{
$y_ht = ($data[$i]/$sum)* $height; // work out height and make sure they don't go larger then the image
imagerectangle($im,$x,$y,$x+$x_width,($y-$y_ht),$red);
imagestring( $im,2,$x-1,$y+10,$data[$i],$black);
$x += ($x_width+20); // set the new distance for the next bar
}
Now we can display the final results
imagejpeg($im);
This bar chart can easily be upgraded.
Full Code
<?php
header("Content-type: image/jpeg");
// read the post data
$data = array('3400','2570','245','473','1000','3456','780');
$sum = array_sum($data);
$height = 255;
$width = 320;
$im = imagecreate($width,$height); // width , height px
$white = imagecolorallocate($im,255,255,255);
$black = imagecolorallocate($im,0,0,0);
$red = imagecolorallocate($im,255,0,0);
imageline($im, 10, 5, 10, 230, $black);
imageline($im, 10, 230, 300, 230, $black);
$x = 15;
$y = 230;
$x_width = 20;
$y_ht = 0;
for ($i=0;$i<7;$i++){
$y_ht = ($data[$i]/$sum)* $height;
imagerectangle($im,$x,$y,$x+$x_width,($y-$y_ht),$red);
imagestring( $im,2,$x-1,$y+10,$data[$i],$black);
$x += ($x_width+20);
}
imagejpeg($im);
?> 


