Working on FIW.ME!

We are currently working on fiw.me a next generation URL shortener!

Generate a simple line graph with Pure PHP

You might want to generate a dynamic line graph to show some statistics, you don’t want to involve yourself into lot of tricky programming? Then let’s just use the PHP GD and Image Functions to do it.

Open a PHP page and add this code:

[php]

header(“Content-Type: image/png”); //this will set header as png image

$im = @imagecreate(800 , 600) //this is size of the canvas

or die(“Cannot Initialize new GD image stream”);

$background_color = imagecolorallocate($im,255 ,255 ,255); //background color as white
$black = imagecolorallocate($im, 0, 0,0);

imageline($im, 80 ,480,650,480, $black); //this for x-axis
imageline($im, 100,40,100,500, $black); //this for y-axis

//division on x-axis
$x_add = 50;
for($i = 0; $i <= 9 ; $i++){
imageline($im, 150+($i*$x_add), 480, 150+($i*$x_add) , 500, $black);
}

//division on y-axis
$y_add = 40;
for($i = 0; $i <= 10 ; $i++){
imageline($im, 80, 480-($i*$y_add), 100 , 480-($i*$y_add), $black);
}

$names_on_x_axis = array(1,2,3,4,5,6,7,8,9,10); // here is where you put the names for values on x-axis
$values_on_x_axis = array(1,2,30,4,5,50,7,8,9,10 ); //put the corresponding value
$y_axis_initial = 1; // here is where you put initial value for y-axis
$y_axis_interval = 10; // here is where you put needed interval value for y-axis

//write values on x – axis,
for($i = 0; $i <= 9 ; $i++){
imagettftext($im, 12,270, 148+($i*$x_add) , 508, $black, ‘font.otf’,$names_on_x_axis[$i] );
}

//write values on y-axis
for($i = 1; $i <= 10 ; $i++){
imagettftext($im, 12,0, 50 , 485-($i*$y_add), $black, ‘font.otf’,$y_axis_initial + (($i*$y_axis_interval)-1) );
}

//calculation part
$total_height = $y_add * 10; //height of graph

//this function will calculate the height for the points
function needed_height($input_value){
global $total_height, $y_add , $y_axis_interval ;
return 480-(($input_value/$y_axis_interval)*$y_add);}

//now to draw line graph
for($v = 2 ;$v<=10 ; $v++)
imageline($im,148+(($v-2)*$x_add),(needed_height($values_on_x_axis[$v-2])),148+((($v-2)+1)*$x_add),(needed_height($values_on_x_axis[$v-1])),$black);

imagepng($im);
imagedestroy($im);

[/php]

and save this page.

You can change values and names for the values by changing the values in arrays named “$names_on_x_axis” and “$values_on_x_axis“,

to change y-axis interval and values edit “$y_axis_initial” “$y_axis_interval“.