萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHPlot 圖表繪製類別完整函式參考與實戰範例

PHPlot 簡介

PHPlot 是純 PHP 繪圖庫,基於 GD,支援長條圖、折線圖、圓餅圖、面積圖、散佈圖等,輸出 PNG/JPG/GIF。適合動態生成報表圖表。

核心函式分類速查

1. 設定函式

  • SetDataType($type):text-data(X 軸標籤+多資料集)、data-data(X 值+Y 值)、data-data-error(含誤差)
  • SetDataValues(array $data):設定資料陣列
  • SetPlotType($type):bars, lines, linepoints, area, points, pie, thinbarline, squared, stackedbars, stackedarea
  • SetFileFormat($fmt):PNG, JPEG, GIF
  • SetUseTTF($bool):是否使用 TrueType 字型
  • SetDefaultTTFont($path):設定 TTF 字型檔路徑

2. 顯示與座標函式

  • SetPlotAreaWorld($xmin, $ymin, $xmax, $ymax):設定資料座標範圍
  • SetPlotAreaPixels($x1, $y1, $x2, $y2):設定繪圖區像素範圍
  • SetXLabelAngle($angle)、SetXTitle($title)、SetYTitle($title)
  • SetTitle($title):主標題
  • SetLegend(array $labels):圖例標籤
  • SetLegendWorld($x, $y):圖例位置(世界座標)
  • SetXTickPos/LabelPos('none'|'plotup'|'plotdown'):X 軸刻度/標籤位置
  • SetPrecisionX/Y($digits):座標精度

3. 顏色與樣式函式

  • SetBackgroundColor($color)、SetPlotBgColor($color)
  • SetGridColor($color)、SetLightGridColor($color)
  • SetLineWidth($width)、SetLineStyles($styles)
  • SetPointShape($shape):rect, circle, diamond, triangle, dot, line, halfline
  • SetPointSize($size)
  • SetTextColor($color)、SetTitleColor($color)、SetTickColor($color)
  • SetDrawPlotAreaBackground(true)
  • SetPlotBorderType('full'|'none'|'sides')

完整範例:客戶滿意度趨勢長條圖

require_once 'phplot.php';

$data = [
    ['2001', 60, 35, 20],
    ['2002', 65, 30, 30],
    ['2003', 70, 25, 40],
    ['2004', 72, 20, 60],
    ['2005', 75, 15, 70],
    ['2006', 77, 10, 80],
    ['2007', 80, 5,  90],
];

$p = new PHPlot(600, 400);
$p->SetDefaultTTFont('./arial.ttf');
$p->SetTitle('PHPlot Customer Satisfaction (estimated)');
$p->SetDataType('text-data');
$p->SetDataValues($data);
$p->SetPlotType('bars');
$p->SetPlotAreaWorld(0, 0, 7, 100);

$p->SetBackgroundColor('#ffffcc');
$p->SetDrawPlotAreaBackground(true);
$p->SetPlotBgColor('#ffffff');
$p->SetPlotBorderType('full');

$p->SetLegend(['Features', 'Bugs', 'Happy Users']);
$p->SetLegendWorld(0.1, 95);

$p->SetXDataLabelPos('plotdown');
$p->SetXTickPos('none');
$p->SetXTickLabelPos('none');
$p->SetYTickPos('none');
$p->SetYTickLabelPos('none');

$p->DrawGraph();

現代替代方案

  • pChart:功能更豐富、支援陰影、漸層、地圖
  • Chart.js / ECharts / Highcharts:前端 JS 渲染,互動性強、卸載伺服器運算
  • Image_Graph (PEAR):較舊但穩定
copyright © 萬盛學電腦網 all rights reserved