Yes its that time again another chart tutorial. This one is going to be a simple bar chart
You can view a demo
HERE
Firstly we are going to set a header type as image
PHP Code:
header("Content-type: image/jpeg");
Now we are going to set some values in an array to use and then all them all together
PHP Code:
$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.
PHP Code:
$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.
PHP Code:
$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.
PHP Code:
$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.
PHP Code:
imageline($im, 10, 5, 10, 230, $black );
imageline($im, 10, 230, 300, 230, $black);
PHP Code:
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.
PHP Code:
$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.
PHP Code:
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
PHP Code:
imagejpeg($im);
This bar chart can easily be upgraded and i will be in the next advance tutorial on bar graphs. Stay tuned.
Full Code
PHP 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);
?>