以下是一个使用PHP创建简单柱状图的实例,我们将使用PHP内置的GD库来生成图表。
```php

// 创建一个300x200像素的图像
$width = 300;
$height = 200;
$image = imagecreatetruecolor($width, $height);
// 分配颜色
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
// 填充背景色
imagefill($image, 0, 0, $white);
// 绘制柱状图数据
$barWidth = $width / 10;
$barHeight = 0;
$dataPoints = [
'点A' => 5,
'点B' => 15,
'点C' => 20,
'点D' => 25,
'点E' => 10
];
// 绘制柱状图
foreach ($dataPoints as $label => $value) {
$barHeight = ($value / max($dataPoints)) * $height;
imagefilledrectangle($image,
($width / count($dataPoints)) * (array_search($label, $dataPoints) % count($dataPoints)),
0,
($width / count($dataPoints)) * (array_search($label, $dataPoints) % count($dataPoints)) + $barWidth,
$barHeight,
$black);
}
// 添加标签
foreach ($dataPoints as $label => $value) {
imagestring($image, 2, ($width / count($dataPoints)) * (array_search($label, $dataPoints) % count($dataPoints)) + $barWidth / 2,
$barHeight + 5,
$label,
$black);
}
// 输出图像
header('Content-Type: image/png');
imagepng($image);
// 释放内存
imagedestroy($image);
>
```
以下是图表数据的表格表示:
| 数据点 | 值 |
|---|---|
| 点A | 5 |
| 点B | 15 |
| 点C | 20 |
| 点D | 25 |
| 点E | 10 |
这段代码创建了一个简单的柱状图,每个柱状图的高度与对应值成正比,并带有标签。图表被保存为PNG格式,并通过HTTP响应输出。







