PHP柱形图生成函数封装详解
下面我将详细介绍如何将JpGraph柱形图生成功能封装成可复用的函数,并提供完整的使用示例。
1. 基础函数封装
/**
* 生成基础柱形图
* @param array $data Y轴数据数组
* @param array $labels X轴标签数组
* @param string $title 图表标题
* @param string $xTitle X轴标题
* @param string $yTitle Y轴标题
* @param string|null $filename 保存文件名(null则直接输出)
* @return bool|string 成功返回true或文件名,失败返回false
*/
function generateBarChart(array $data, array $labels, string $title,
string $xTitle, string $yTitle, ?string $filename = null) {
try {
// 引入库文件
require_once 'jpgraph/src/jpgraph.php';
require_once 'jpgraph/src/jpgraph_bar.php';
// 创建图表对象
$graph = new Graph(800, 400);
$graph->SetScale('textlin');
// 设置标题
$graph->title->Set($title);
$graph->xaxis->title->Set($xTitle);
$graph->yaxis->title->Set($yTitle);
// 创建柱形图
$barplot = new BarPlot($data);
$barplot->SetFillColor('skyblue');
$barplot->SetWidth(0.6);
// 添加到图表
$graph->Add($barplot);
$graph->xaxis->SetTickLabels($labels);
// 输出结果
if ($filename) {
$graph->Stroke($filename);
return $filename;
} else {
$graph->Stroke();
return true;
}
} catch (Exception $e) {
error_log('图表生成错误: ' . $e->getMessage());
return false;
}
}2. 高级封装函数(支持多配置)
/**
* 高级柱形图生成函数
* @param array $data 数据数组(支持单组或多组)
* @param array $labels X轴标签
* @param array $options 配置选项
* @return bool|string
*/
function generateAdvancedBarChart(array $data, array $labels, array $options = []) {
try {
require_once 'jpgraph/src/jpgraph.php';
require_once 'jpgraph/src/jpgraph_bar.php';
// 合并默认配置
$defaults = [
'width' => 800,
'height' => 400,
'title' => '销售统计',
'xTitle' => '月份',
'yTitle' => '销量',
'colors' => ['skyblue'],
'filename' => null,
'showValues' => true,
'gradient' => false,
'shadow' => false,
'grouped' => false
];
$options = array_merge($defaults, $options);
// 创建图表
$graph = new Graph($options['width'], $options['height']);
$graph->SetScale('textlin');
$graph->SetMargin(50, 30, 40, 50);
// 设置标题
$graph->title->Set($options['title']);
$graph->xaxis->title->Set($options['xTitle']);
$graph->yaxis->title->Set($options['yTitle']);
// 处理多组数据
if ($options['grouped'] && is_array($data[0])) {
$bars = [];
foreach ($data as $i => $dataset) {
$bar = new BarPlot($dataset);
$color = $options['colors'][$i % count($options['colors'])];
$bar->SetFillColor($color);
if ($options['gradient']) {
$bar->SetFillGradient($color, 'white', GRAD_VER);
}
if ($options['shadow']) {
$bar->SetShadow('darkgray', 3, 2);
}
if ($options['showValues']) {
$bar->value->Show();
$bar->value->SetFormat('%d');
}
$bars[] = $bar;
}
$gbplot = new GroupBarPlot($bars);
$gbplot->SetWidth(0.7);
$graph->Add($gbplot);
} else {
// 单组数据处理
$barplot = new BarPlot($data);
$barplot->SetFillColor($options['colors'][0]);
$barplot->SetWidth(0.6);
if ($options['gradient']) {
$barplot->SetFillGradient($options['colors'][0], 'white', GRAD_VER);
}
if ($options['shadow']) {
$barplot->SetShadow('darkgray', 3, 2);
}
if ($options['showValues']) {
$barplot->value->Show();
$barplot->value->SetFormat('%d');
}
$graph->Add($barplot);
}
// 设置X轴标签
$graph->xaxis->SetTickLabels($labels);
// 输出结果
if ($options['filename']) {
$graph->Stroke($options['filename']);
return $options['filename'];
} else {
$graph->Stroke();
return true;
}
} catch (Exception $e) {
error_log('图表生成错误: ' . $e->getMessage());
return false;
}
}3. 函数使用示例
3.1 基础函数使用
// 数据准备 $months = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']; $sales = [120, 150, 180, 210, 250, 300, 320, 310, 280, 260, 230, 200]; // 生成图表 generateBarChart( $sales, $months, '2025年计算机图书销售情况', '月份', '销量(本)', 'book_sales.png' );
3.2 高级函数使用
// 多组数据准备 $data = [ [120,150,180,210,250,300], // 编程类 [80,90,110,130,150,180], // 办公类 [60,70,85,95,110,130] // 设计类 ]; $labels = ['1月','2月','3月','4月','5月','6月']; // 配置选项 $options = [ 'title' => '2025上半年各类图书销售对比', 'colors' => ['#4285F4', '#EA4335', '#FBBC05'], 'gradient' => true, 'shadow' => true, 'grouped' => true, 'filename' => 'category_sales.png' ]; // 生成图表 generateAdvancedBarChart($data, $labels, $options);
4. 封装函数参数详解
基础函数参数
高级函数配置选项
5. 封装优势说明
代码复用性:避免重复编写相同的图表生成代码
参数标准化:统一参数格式,降低使用难度
错误处理:内置异常捕获机制
灵活性:通过配置选项支持多种图表样式
可扩展性:易于添加新的图表功能
6. 实际应用建议
可将这些函数放入单独的
chart_utils.php文件中在需要生成图表的地方包含该文件即可
对于频繁使用的配置,可以预定义配置模板:
// 预定义公司标准样式 $companyStyle = [ 'width' => 900, 'height' => 500, 'colors' => ['#1E88E5', '#43A047', '#F4511E'], 'gradient' => true, 'shadow' => true ]; // 使用时合并配置 $options = array_merge($companyStyle, [ 'title' => '季度销售报告', 'grouped' => true ]);
通过这种封装方式,可以大大简化项目中图表生成的复杂度,提高开发效率。