Computers

Drawing a Bar Chart Using PHP

We can use the image drawing property in PHP to draw basic bar charts (simple bar charts / multiple bar charts). Following are the simple steps that need to be followed in order to plot the bar chart for the table given below.

Step 01 :

Define X coordinates and Y coordinates, this can be input using a database or using an associative array.

$x_values = array(1,2,3,4,5,6,7,8,9,10);
$y_values = array(500,1000,750,1200,1300,650,870,400,800,1100);

Step 02:

Get the total number of Bars we are going to plot and define the image size.

$columns = count($x_values);
$width = 600;
$height = 400;

Step 03:

Set the margins and padding required and calculate the column width.

$margin = 20;
$padding = 10;
$column_width = ($width-$margin*2) / $columns
;

Step 04:

Set the image variables with color variables

$im = imagecreate($width,$height);

$white = imagecolorallocate ($im,0xff,0xff,0xff);
$black = imagecolorallocate ($im,0x00,0x00,0x00);
$red = imagecolorallocate ($im,0xff,0x00,0x00);
$blue = imagecolorallocate ($im,0x00,0x33,0xff);
$gray = imagecolorallocate ($im,0xcc,0xcc,0xcc);

Step 05:

Fill the background color

imagefilledrectangle($im,0,0,$width,$height,$white);

Step 06:

Find the maximum value we are going to plot in order to calculate the proportionate heights.

$maxv = 0;
for($i=0;$i<$columns;$i++)$maxv = max($y_values[$i],$maxv);

Step 07:

Draw the horizontal lines.

imageline($im,$margin*3-10,$height-$margin*2,$width-$margin+$padding,$height-$margin*2,$gray);
for($i=0;$i<$columns;$i++){
$column_height = $height * ( $y_values[$i] / $maxv) ;
imageline($im,$margin*3-10,$height-$column_height+$margin*2,$width-$margin+$padding,$height-$column_height+$margin*2,$gray);
}

Step 08:

Plot each and every bar.

for($i=0;$i<$columns;$i++){
$column_height = $height * ( $y_values[$i] / $maxv) ;
$x1 = $i*$column_width + $margin*3 ;
$y1 = $height-$column_height+$margin*2;
$x2 = (($i+1)*$column_width)-$padding +$margin*2;
$y2 = $height-$margin*2;
imagefilledrectangle($im,$x1,$y1,$x2,$y2,$blue); // Bar color
ImageString($im,5,$x1,$y2+10,$x_values[$i],$black); // X labels
ImageString($im,5,10,$y1-10,round($y_values[$i],0),$black); // Y labels
}
ImageString($im,5,$width-$margin*2,$y2+25,'Year',$red); // X title
ImageString($im,5,10,10,'Profit',$red); // Y title

Step 09:

Now have to output the chart

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

or you can save the chart

imagepng($im,'graph.png');

clear up memory

imagedestroy($im);

That’s all, can download the full PHP code with comments using graph.php

Share this post

Related Posts

3 thoughts on “Drawing a Bar Chart Using PHP”

  1. Hanxlk says:

    Useful Article.. Thank you.. and keep writing 😉

  2. Ansh Lucky Sri Jay says:

    wow, good article..!
    🙂

  3. vignesh says:

    Nice article..But sadly I need to create horizontal bar chart..Do u have any idea?

Comments are closed.