一、
<?php
/**
* 生成柱形图并保存为图片
* @param array $data Y轴数据数组(必填)
* @param array $labels X轴标签数组(必填)
* @param string $title 图表主标题(默认'销售统计')
* @param string $xTitle X轴标题(默认'月份')
* @param string $yTitle Y轴标题(默认'销量')
* @param string|null $filename 输出文件路径(null则直接输出)
* @param int $width 图像宽度(默认800)
* @param int $height 图像高度(默认400)
* @param array $colors 柱形颜色数组(默认['#4285F4'])
* @param bool $showValues 是否显示数值(默认true)
* @param string $valueFormat 数值格式(默认'%d')
* @param float $barWidth 柱形宽度比例0-1(默认0.6)
* @param bool $gradient 是否启用渐变(默认false)
* @param string $gradientStart 渐变起始色(默认'navy')
* @param string $gradientEnd 渐变结束色(默认'lightblue')
* @param bool $shadow 是否显示阴影(默认false)
* @return bool|string 成功返回true或文件名,失败返回false
*/
function generateBarChart(
array $data,
array $labels,
string $title = '销售统计',
string $xTitle = '月份',
string $yTitle = '销量',
?string $filename = null,
int $width = 800,
int $height = 400,
array $colors = ['#4285F4'],
bool $showValues = true,
string $valueFormat = '%d',
float $barWidth = 0.6,
bool $gradient = false,
string $gradientStart = 'navy',
string $gradientEnd = 'lightblue',
bool $shadow = false
) {
// 检查必要库文件
if (!file_exists('jpgraph/src/jpgraph.php') ||
!file_exists('jpgraph/src/jpgraph_bar.php')) {
error_log('JpGraph库文件缺失');
return false;
}
// 验证数据
if (count($data) !== count($labels)) {
error_log('数据与标签数量不匹配');
return false;
}
try {
// 引入库文件
require_once 'jpgraph/src/jpgraph.php';
require_once 'jpgraph/src/jpgraph_bar.php';
// 创建图表对象
$graph = new Graph($width, $height);
$graph->SetScale('textlin');
$graph->SetMargin(50, 30, 40, 50);
// 设置标题
$graph->title->Set($title);
$graph->title->SetFont(FF_SIMSUN, FS_BOLD, 14);
$graph->xaxis->title->Set($xTitle);
$graph->yaxis->title->Set($yTitle);
// 创建柱形图
$barplot = new BarPlot($data);
$barplot->SetFillColor($colors[0]);
$barplot->SetWidth($barWidth);
// 可选样式设置
if ($gradient) {
$barplot->SetFillGradient($gradientStart, $gradientEnd, GRAD_VER);
}
if ($shadow) {
$barplot->SetShadow('darkgray', 3, 2);
}
if ($showValues) {
$barplot->value->Show();
$barplot->value->SetFormat($valueFormat);
$barplot->value->SetFont(FF_SIMSUN, FS_NORMAL, 10);
}
// 组合输出
$graph->Add($barplot);
$graph->xaxis->SetTickLabels($labels);
// 输出结果
if ($filename) {
$graph->Stroke($filename);
return file_exists($filename) ? $filename : false;
} else {
$graph->Stroke();
return true;
}
} catch (Exception $e) {
error_log('图表生成错误: ' . $e->getMessage());
return false;
}
}二、
<?php
// 示例数据
$months = ['1月','2月','3月','4月','5月','6月'];
$sales = [120, 150, 180, 210, 250, 300];
// 调用函数生成图表
$result = generateBarChart(
$sales,
$months,
'2025上半年销售报告',
'月份',
'销量(台)',
'sales_report.png',
900, 500,
['#34A853'],
true,
'%d台',
0.7,
true,
'#0F9D58',
'#B7E1CD',
true
);
if ($result) {
echo "图表生成成功: $result";
} else {
echo "图表生成失败";
}
?>