PHP生成条形图的方法

这篇文章主要介绍了PHP生成条形图的方法,可实现生成柱状的条形图,适用于一些类似柱状图显示报表的场合,具有一定的实用价值,需要的朋友可以参考下

本文实例讲述了PHP生成条形图的方法,分享给大家供大家参考,具体实现方法如下:

  1. <?php
  2. // create an array of values for the chart. These values
  3. // could come from anywhere, POST, GET, database etc.
  4. $values = array(23,32,35,57,12,3,36,54,32,15,43,24,30);
  5. // now we get the number of values in the array. this will
  6. // tell us how many columns to plot
  7. $columns = count($values);
  8. // set the height and width of the graph image
  9. $width = 300;
  10. $height = 200;
  11. // Set the amount of space between each column
  12. $padding = 5;
  13. // Get the width of 1 column
  14. $column_width = $width / $columns ;
  15. // set the graph color variables
  16. $im = imagecreate($width,$height);
  17. $gray = imagecolorallocate ($im,0xcc,0xcc,0xcc);
  18. $gray_lite = imagecolorallocate ($im,0xee,0xee,0xee);
  19. $gray_dark = imagecolorallocate ($im,0x7f,0x7f,0x7f);
  20. $white = imagecolorallocate ($im,0xff,0xff,0xff);
  21. // set the background color of the graph
  22. imagefilledrectangle($im,0,0,$width,$height,$white);
  23. // Calculate the maximum value we are going to plot
  24. $max_value = max($values);
  25. // loop over the array of columns
  26. for($i=0;$i<$columns;$i++)
  27. {
  28. // set the column hieght for each value
  29. $column_height = ($height / 100) * (( $values[$i] / $max_value)
  30. *100);
  31. // now the coords
  32. $x1 = $i*$column_width;
  33. $y1 = $height-$column_height;
  34. $x2 = (($i+1)*$column_width)-$padding;
  35. $y2 = $height;
  36. // write the columns over the background
  37. imagefilledrectangle($im,$x1,$y1,$x2,$y2,$gray);
  38. // This gives the columns a little 3d effect
  39. imageline($im,$x1,$y1,$x1,$y2,$gray_lite);
  40. imageline($im,$x1,$y2,$x2,$y2,$gray_lite);
  41. imageline($im,$x2,$y1,$x2,$y2,$gray_dark);
  42. }
  43. // set the correct png headers
  44. header ("Content-type: image/png");
  45. // spit the image out the other end
  46. imagepng($im);
  47. ?>