I this blog I am sharing a simple code to draw a line graph using php. Here I am using a value_array to hold my data for drawing the graph. If we wants to draw the graph based on records from database just replace the values of $value_array. Here I’m assumed that there is only 12 in that array.
$value_array=array();
$value_array[1] = 3500;
$value_array[2] = 2000;
$value_array[3] = 5000;
$value_array[4] = 500;
$value_array[5] = 2500;
$value_array[6] = 5;
$value_array[7] = 4250;
$value_array[8] = 1110;
$value_array[9] = 3720;
$value_array[10] = 1190;
$value_array[11] = 2670;
$value_array[12] = 440;
$array_count=count($value_array);
$imagewd=600; //X value
$imageht=550; //Y value
$image=imagecreate($imagewd,$imageht);
$colo=imagecolorallocate($image,55,55,55);
$drcol=imagecolorallocate($image,00,00,00);
$graph_col=imagecolorallocate($image,00,00,255);
$text_color=imagecolorallocate($image,00,200,20);
//-------------Horizontal Lines----------------------------------------------
$cord1 = 50;
while($cord1<=500){
imageline($image,0,$cord1,900,$cord1,$drcol);
$cord1 = $cord1+50;
}
//-------------End Horizontal Lines------------------------------------------
//-------------Vertical Lines------------------------------------------------
$cord2 = 50;
while($cord2<=600){
imageline($image,$cord2,0,$cord2,600,$drcol);
$cord2 = $cord2+50;
}
//-------------End Vertical Lines-------------------------------------------
$x1=0;
$y1=550;
$x2=0;
$y2=0;
imagesetthickness($image,3);//code changing thickness of graph
//Drawing Graph depending upon values---------------------
for($i=1;$i<=$array_count;$i++){
$graph_value=$value_array[$i]*50/500;
$x2=$x1+50;
$y2=550-$graph_value;
imageline($image,$x1,$y1,$x2,$y2,$graph_col);
imagestring($image,4,$x2-10,$y2-13,$value_array[$i],$text_color); //Printing value's of each points
$x1=$x2;
$y1=$y2;
}
header("content-Type:image/jpeg");
imagejpeg($image);
imagedestroy($image);
?>
I used following code to embed this graph to my html page.
jan
feb
mar
apr
may
jun
jul
aug
sep
oct
nov
dec