php.ini 中取消註釋 extension=gd2(PHP 7.2+ 為 extension=gd)/vendor/jpgraph)composer require jpgraph/jpgraph 或手動配置 include_path| 類 | 用途 |
|---|---|
| Graph | 畫布容器,管理尺寸、邊距、標題、圖例 |
| Plot | 繪圖基類:LinePlot(折線)、BarPlot(柱狀)、PiePlot(餅圖)、ScatterPlot(散點) |
| Scale | 座標系:TextLin(文本X+線性Y)、LinLin(雙線性)、LogLin(對數) |
| Legend | 圖例管理 |
<?php
require_once 'vendor/jpgraph/src/jpgraph.php';
require_once 'vendor/jpgraph/src/jpgraph_line.php';
// 數據
$ydata = [12, 4, 9, 15, 11, 10, 9, 7, 15, 7];
// 創建畫布:寬 350、高 250、自動緩存文件名
$graph = new Graph(350, 250, 'auto');
// 設置座標系:X 軸文本標籤,Y 軸線性
$graph->SetScale('textlin');
// 創建折線圖對象
$line = new LinePlot($ydata);
$line->SetColor('blue'); // 線條顏色
$line->SetWeight(2); // 線條粗細
$line->SetLegend('銷售額'); // 圖例文字
// 添加到畫布
$graph->Add($line);
// 圖表美化
$graph->title->Set('月度銷售趨勢');
$graph->title->SetFont(FF_FONT1, FS_BOLD, 14);
$graph->xaxis->title->Set('月份');
$graph->yaxis->title->Set('萬元');
$graph->xaxis->SetTickLabels(['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月']);
$graph->xaxis->SetLabelAngle(45); // 傾斜標籤防重疊
// 輸出圖片(直接輸出到瀏覽器)
$graph->Stroke();
?>
<?php
require_once 'jpgraph.php';
require_once 'jpgraph_bar.php';
require_once 'jpgraph_line.php';
$barData = [120, 135, 142, 158, 165];
$lineData = [12.5, 13.2, 11.8, 14.5, 15.0];
$graph = new Graph(500, 350);
$graph->SetScale('textlin');
$graph->SetMargin(60, 60, 40, 60); // 左右上下邊距
// 左Y軸:柱狀圖
$bar = new BarPlot($barData);
$bar->SetFillColor('#4CAF50');
$bar->SetLegend('銷量');
// 右Y軸:折線圖
$line = new LinePlot($lineData);
$line->SetColor('#FF5722');
$line->SetWeight(3);
$line->SetLegend('增長率(%)');
// 添加到畫布,指定 Y 軸
$graph->Add($bar);
$graph->AddY2($line); // 關鍵:添加到第二 Y 軸
// 右Y軸格式化
$graph->y2axis->SetColor('#FF5722');
$graph->y2axis->title->Set('增長率(%)');
$graph->y2axis->title->SetColor('#FF5722');
$graph->Stroke();
?>
<?php
require_once 'jpgraph.php';
require_once 'jpgraph_pie.php';
$data = [45, 25, 15, 10, 5];
$labels = ['搜索引擎', '直接訪問', '外鏈引薦', '社交媒體', '其他'];
$graph = new PieGraph(400, 300);
$graph->title->Set('流量來源分布');
$pie = new PiePlot3D($data); // 3D 效果
$pie->SetLegends($labels);
$pie->SetCenter(0.5, 0.55);
$pie->SetSize(180);
$pie->SetTheme('pastel'); // 內置配色主題
$pie->value->Show(false); // 隱藏數值,僅圖例顯示
$graph->Add($pie);
$graph->Stroke();
?>
| 問題 | 解決方案 |
|---|---|
| 中文亂碼/方塊 | 設置字體:$graph->SetFont('SimHei', FS_NORMAL, 12) 需服務器安裝中文字體 |
| 生成圖片空白 | 檢查 ob_start() 是否在前面開啟,輸出前需 ob_clean() |
| 性能差 | 啟用緩存:$graph->SetCacheDir('/tmp/jpgraph_cache'),複用圖片 |
| 坐標軸標籤重疊 | SetLabelAngle(45)、SetTextAlign('right', 'center') |
JpGraph 純 PHP 繪圖,CPU 密集型,高併發下性能瓶頸明顯。建議:
JpGraph 適合:低頻報表生成、無前端環境的後台管理系統、簡單圖表需求。核心流程:Graph → Scale → Plot → Add → Stroke。掌握座標系選擇、雙Y軸組合、主題美化三大技巧,即可應對 90% 業務場景。