Create Dynamic Bar Graph/Chart in php

In this article, I will show how to dynamically create bar graph in PHP. I have created PHP script to create a bar graph in php such that x-scale and y-scale changes dynamically.

Example : Create dynamic Graph/Chart image page using MySQL&PHP

<?php

$hrs= array( "0" => 11, "1" => 12 ,"2" => 13 ,"3" => 14 ,"4" => 15);

$data= array ("0" => 15 ,"1" => 11, "2" => 5, "3" => 15 ,"4" => 17 );

$hrs_len=sizeof($hrs);

if(!empty($data) && !empty($hrs))
{
$data=array_combine($hrs,$data);

$image_width=($hrs_len+1)*32;
$image_height=80;
$padding=20;


$graph_width=$image_width - $padding * 2;
$graph_height=$image_height - $padding * 2;
$image=imagecreate($image_width,$image_height);
$bar_width=25;
$total_bars=count($data);
$gap= 5;
$background_color=imagecolorallocate($image,255,255,255);
$border_color=imagecolorallocate($image,255,255,255);
$line_color=imagecolorallocate($image,255,255,255);


$max_value=max($data);
$ratio= $graph_height/$max_value;
$horizontal_data=20;
$horizontal_gap=$graph_height/$horizontal_data;
for($i=1;$i<=$horizontal_data;$i++){
$y=$image_height - $padding - $horizontal_gap * $i ;
imageline($image,$padding,$y,$image_width-$padding,$y,$line_color);
$v=intval($horizontal_gap * $i /$ratio);
}
   $bar_color=imagecolorallocate($image,50,205,50);
for($i=0;$i< $total_bars; $i++){
list($key,$value)=each($data);
$x1= $padding + $gap + $i * ($gap+$bar_width) ;
$x2= $x1 + $bar_width;
$y1=$padding +$graph_height- intval($value * $ratio) ;
$y2=$image_height-$padding;

imagestring($image,0,$x1+3,$y1-10,$value,$bar_color);
imagestring($image,0,$x1+3,$image_height-15,$key,$bar_color);
imagefilledrectangle($image,$x1,$y1,$x2,$y2,$bar_color);
}
header("Content-type:image/png");
imagepng($image);
}
?>


I hope this example will help you to create Dynamic Bar Graph/Chart in php.