Hi; Although I am a big fan of jPgraph, I am gradually learning to use less elaborate GD code in php for simple tasks. I just worked out a script to create a tiny simple horizontal stacked bar graph (that I use in table cells with related data). I thought it might be of interest to other newbies out there.

I call the file "_func_GD_hbar_multival.php" and include() it in scripts where I need to use it.

<?php
function makeChart($info, $name) {
$max=array_sum($info);
$height=15; 
$width=100;
$barstart=0;
$barwidth=100;
$im = ImageCreate($width+1, $height+1);
$white = ImageColorAllocate ($im, 255, 255, 255);
$black = ImageColorAllocate ($im, 0, 0, 0);
$red = ImageColorAllocate($im, 255,0,0);
$yelo = ImageColorAllocate($im, 255,255,0);
$green = ImageColorAllocate($im, 0,128,0);
$grey = ImageColorAllocate($im, 60,20,100);
//you can add other colors if you know the RGB values.

// Create initial image w/borders  
ImageFilledRectangle($im, 0, 0, $width, $height,$white); ImageRectangle($im, 0, 0, $width,$height,$black); $horiz=0; ImageRectangle($im, $barstart, $horiz, $barwidth,$horiz+$height,$black); foreach ($info as $clr=>$profcount) { //note that I use color names as keys in the $info array if($profcount=="" or is_null($profcount)) {$profcount=0;} else {} $perc=$profcount/$max; // a decimal amount $Xperc=$perc*100; ImageFilledRectangle($im, $barstart, $horiz, $barstart+$Xperc,$horiz+$height,$$clr); $barstart=$barstart+$Xperc; //this shifts the beginning of the next color segment to the end of the prior one } ImageJpeg ($im,$name); //the file will be saved in the script directory ImageDestroy($im);} // USE THIS CODE IN SCRIPT FILES WHERE YOU NEED TO SHOW THE BAR /* // if I am displaying a multiple-row table with a bargraph in each row, I use the rowcounter value to give a unique name to the bargraph .jpg for that row, otherwise they will all show the same graph $name="tmp".$rowcounter.".jpg"; $info=array('red'=>$profcounts[Basic], 'yelo'=>$profcounts[Minimal],'green'=>$profcounts[Proficient],'grey'=>$profcounts[undefined]); call_user_func('makeChart', $info,$name); echo "<img src=\"$name\" title=\"Image\" alt=\"Image\" />"; */ ?>

Hope this is of use to someone.

    Write a Reply...