先把数据和图例对应起来
下面用三组演示数据:A 为 50,B 为 30,C 为 20。总量是 100,所以 A 占半圆,B 和 C 分别占 108° 和 72°。演示数据与旧图无关,读者可以按这些值重新生成和核对结果。
| 类别 | 数值 | 扇区角度 |
|---|---|---|
| A | 50 | 180° |
| B | 30 | 108° |
| C | 20 | 72° |
逐段累加角度并输出 PNG
<?php
$series = [
['A', 50, [44, 111, 199]],
['B', 30, [31, 137, 102]],
['C', 20, [174, 90, 34]],
];
$total = array_sum(array_column($series, 1));
if ($total <= 0) {
throw new RuntimeException('The total must be positive');
}
$im = imagecreatetruecolor(400, 280);
$white = imagecolorallocate($im, 255, 255, 255);
$ink = imagecolorallocate($im, 30, 30, 30);
imagefill($im, 0, 0, $white);
$sum = 0;
foreach ($series as $index => [$label, $value, $rgb]) {
$start = (int) round($sum / $total * 360);
$sum += $value;
$end = (int) round($sum / $total * 360);
$color = imagecolorallocate($im, ...$rgb);
if ($end > $start) {
imagefilledarc($im, 140, 140, 220, 220, $start, $end, $color, IMG_ARC_PIE);
}
$y = 85 + $index * 32;
imagefilledrectangle($im, 280, $y, 294, $y + 14, $color);
imagestring($im, 4, 305, $y, "{$label}: {$value}", $ink);
}
imagepng($im, __DIR__ . '/pie.png');
代码要求启用 GD。按累计份额计算边界,并让上一扇区的终点与下一扇区的起点一致,可以避免各扇区单独舍入后产生空隙。把某一项设为零,检查它是否没有扇区;要对外接收数据时,还应拒绝负值等无效输入。
原示例的厚度效果
下图保留的是旧示例的效果。它用额外绘制层表现厚度。要精确比较类别占比,仍应把数值和类别一同列出,尤其是最接近的两组。

旧代码的饼图效果,数值与上面的演示数据分别对应各自示例。