GORAGOD.com

freelance, web developer, web designer, hosting, domain name

Simple PHP Bar Graph using GD library

เราสามารถสร้าง bar graph แบบง่ายๆ ด้วย GD Library (PHP) ได้
<html>
<head>
<title>Simple Bar Graph</title>
</head>
<body>
<?php
//ข้อมูล
$data = array('100', '200', '300', '400', '500', '350', '270');
$cols = array('Sun', 'Mon', 'Tue', 'Wen', 'Thu', 'Fir', 'Sat');
// find the largest data
$max = 0;
for ($i = 0; $i < 7; $i++) {
    if ($data[$i] > $max) {
        $max = $data[$i];
    }
}
// image width , height px
$im = imagecreate(320, 255);

// ค่าสีต่างๆ
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$red = imagecolorallocate($im, 255, 0, 0);
$green = imagecolorallocate($im, 0, 255, 0);
$blue = imagecolorallocate($im, 0, 0, 255);

// bar x1 position
$x = 15;
// bar $y1 position
$y = 230;
// width of bars
$x_width = 20;
// height of bars, will be calculated later
$y_ht = 0;
// get into some meat now, cheese for vegetarians;
for ($i = 0; $i < 7; $i++) {
    // no validation so check if $max = 0 later;
    $y_ht = ($data[$i] / $max) * 100;
    imagerectangle($im, $x, $y, $x + $x_width, ($y - $y_ht), $red);
    imagestring($im, 2, $x - 1, $y + 1, $cols[$i], $black);
    imagestring($im, 2, $x, $y - $y_ht - 15, $data[$i], $black);
    // 20 is diff between two bars;
    $x += ($x_width + 20);
}

// draw X, Y Co-Ordinate
imageline($im, 10, 5, 10, 230, $blue);
imageline($im, 10, 230, 300, 230, $blue);

//เขียนข้อความ
imagestring($im, 3, 15, 5, "Students", $black);
imagestring($im, 5, 100, 50, "Simple Graph", $red);
imagestring($im, 5, 90, 75, "by Goragod.com", $green);

// สร้างรูปภาพ
imagejpeg($im, "graph.jpeg", 90);
imagedestroy($im);
echo "<img src='graph.jpeg'><p></p>";
?>
</body>
</html>

ผลลัพท์
0SHAREFacebookLINE it!
^