首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

JpGraph PHP 圖表庫安裝配置與資料庫整合完整指南

     編輯:PHP 相關知識

安裝前置需求

  • PHP ≥ 4.0.4(建議 5.6+ / 7.x / 8.x)
  • GD Library ≥ 2.0(含 FreeType、PNG、JPEG 支援)
  • 驗證:php -m | grep gd 或 phpinfo() 查看 GD 區塊

安裝步驟

  1. 下載:官網最新版(免費版 / 專業版)
  2. 解壓至專案目錄,如 /var/www/html/jpgraph/
  3. 配置 jpgraph.php(第 35、38 行附近):
    // 快取目錄(需可寫入)
    define('CACHE_DIR', '/tmp/jpgraph_cache/');  // Linux
    // define('CACHE_DIR', 'C:/tmp/jpgraph_cache/'); // Windows
    
    // 字型目錄
    define('TTF_DIR', '/usr/share/fonts/truetype/'); // Linux
    // define('TTF_DIR', 'C:/Windows/Fonts/'); // Windows
  4. 建立快取目錄並給權限:mkdir -p /tmp/jpgraph_cache && chmod 777 /tmp/jpgraph_cache
  5. 測試:將 src/Examples/ 下範例複製至 Web 根目錄,瀏覽驗證。

資料庫整合實戰:從 MySQL 繪製長條圖

<?php
require_once 'jpgraph/src/jpgraph.php';
require_once 'jpgraph/src/jpgraph_bar.php';

// 1. 連線資料庫
$pdo = new PDO('mysql:host=localhost;dbname=jpg;charset=utf8', 'root', '');
$stmt = $pdo->query('SELECT number FROM test ORDER BY id');
$values = $stmt->fetchAll(PDO::FETCH_COLUMN);

// 2. 建立圖表
$graph = new Graph(400, 200, 'auto');
$graph->SetScale('textlin');
$graph->img->SetMargin(40, 130, 20, 40);
$graph->SetShadow();

// 3. 長條圖資料
$bplot = new BarPlot($values);
$bplot->SetFillColor('orange');
$bplot->SetLegend('Result');

// 4. 組裝
$graph->Add($bplot);
$graph->title->Set('資料庫驅動長條圖');
$graph->xaxis->title->Set('項目');
$graph->yaxis->title->Set('數值');
$graph->title->SetFont(FF_FONT1, FS_BOLD);
$graph->yaxis->title->SetFont(FF_FONT1, FS_BOLD);
$graph->xaxis->title->SetFont(FF_FONT1, FS_BOLD);

// 5. 輸出
$graph->Stroke();
?>

常見圖表類型與對應類別

圖表IncludePlot Class
長條圖jpgraph_bar.phpBarPlot
折線圖jpgraph_line.phpLinePlot
圓餅圖jpgraph_pie.phpPiePlot / PiePlot3D
面積圖jpgraph_line.phpAreaPlot
散佈圖jpgraph_scatter.phpScatterPlot
雷達圖jpgraph_radar.phpRadarPlot
Gantt 圖jpgraph_gantt.phpGanttChart

效能優化建議

  • 啟用快取:$graph->SetCacheDir(CACHE_DIR); 避免重複運算。
  • 大量資料點(>1000)建議採樣或使用 img->SetAntiAliasing(false) 關閉抗鋸齒。
  • 僅載入需要的 Plot 類別,減少記憶體佔用。
  • 生產環境關閉錯誤顯示,改記錄日誌。

遷移提醒

JpGraph 免費版授權為 QPL 1.0,商業專案需購買專業授權。現代替代方案:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved