PHPlot 是純 PHP 實現的繪圖庫,基於 GD 擴展,支援長條圖、折線圖、圓餅圖、面積圖、散點圖等。無需外部程式,部署簡單,適合動態生成報表圖片。
https://sourceforge.net/projects/phplot/ 或本站鏡像。phplot.php 放入專案目錄。phpinfo() 檢查)。<?php
require_once 'phplot.php';
// 1. 建立畫布 (寬, 高)
$plot = new PHPlot(600, 400);
// 2. 設定字型(支援 TTF 中文)
$plot->SetDefaultTTFont(__DIR__ . '/fonts/msjh.ttc'); // 微軟正黑體
// 3. 設定標題
$plot->SetTitle('客戶滿意度趨勢');
// 4. 選擇資料類型
// 'text-data':X 軸為標籤,每筆資料 [label, y1, y2, ...]
// 'data-data':X 軸為數值,每筆 [label, x, y1, y2, ...]
$plot->SetDataType('text-data');
// 5. 喂入資料
$data = [
['2018', 65, 30, 40],
['2019', 70, 25, 50],
['2020', 75, 20, 65],
['2021', 78, 15, 80],
['2022', 80, 10, 90],
];
$plot->SetDataValues($data);
// 6. 選擇圖表類型
$plot->SetPlotType('bars'); // 'lines', 'linepoints', 'pie', 'points', 'area'
// 7. 微調外觀(選用)
$plot->SetBackgroundColor('#ffffcc');
$plot->SetPlotBgColor('#ffffff');
$plot->SetDrawPlotAreaBackground(true);
$plot->SetPlotBorderType('full');
$plot->SetLegend(['功能數', 'Bug數', '滿意用戶']);
$plot->SetLegendWorld(0.5, 95); // 圖例位置(世界座標)
$plot->SetXDataLabelPos('plotdown'); // X 標籤位置
$plot->SetXTickPos('none'); // 隱藏 X 刻度線
$plot->SetYTickLabelPos('both'); // Y 軸兩側顯示標籤
// 8. 輸出圖片
$plot->DrawGraph();
| 分類 | 代表方法 | 說明 |
|---|---|---|
| 資料與類型 | SetDataType() | text-data / data-data / data-data-error |
SetDataValues() | 傳入二維陣列 | |
SetPlotType() | bars, lines, linepoints, pie, points, area, thinbarline | |
SetPlotAreaWorld() | 手動設定座標範圍 (xmin, ymin, xmax, ymax) | |
| 外觀與樣式 | SetBackgroundColor() | 整張圖背景色 |
SetPlotBgColor() | 繪圖區背景色 | |
SetLineWidth() | 線條寬度 | |
SetPointShape() | 點形狀:rect, circle, diamond, triangle, dot, line | |
| 座標軸與刻度 | SetXTickLabelPos() | X 軸標籤位置:none, plotdown, plotup, both |
SetYTickIncrement() | Y 軸刻度間距 | |
SetPrecisionY() | Y 軸小數位數 | |
SetXDataLabelMaxlength() | X 標籤最大長度(超出截斷) | |
| 顏色控制 | SetGridColor() | 網格線顏色 |
SetTextColor() | 文字顏色 | |
SetTitleColor() | 標題顏色 |
// 預設 PNG,可改 JPEG/GIF
$plot->SetFileFormat('png'); // 需 GD 支援
// 直接輸出(已在 DrawGraph 內處理 header)
// 若需存檔:
$plot->SetPrintImage(false); // 關閉直接輸出
$plot->DrawGraph();
$img = $plot->GetImage(); // 取得 GD 資源
imagepng($img, 'chart.png');
imagedestroy($img);
SetDefaultTTFont() 指向完整路徑的 .ttf/.ttc 字型檔。pChart、Chart.js(前端渲染)或 Image_Graph(PEAR)。PHPlot 以零依賴、純 PHP、API 直覺著稱,適合中小型專案快速生成靜態統計圖。掌握 SetDataType、SetPlotType、SetDataValues 三大核心,配合 TTF 字型即可產出專業中文圖表。