您好!欢迎访问家园网-www.jy.wang!

家园网

PHP柱形图生成函数封装详解

网络 作者:本站 点击:

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. 封装函数参数详解

基础函数参数

参数类型必填说明
$dataarrayY轴数据数组
$labelsarrayX轴标签数组
$titlestring图表主标题
$xTitlestringX轴标题
$yTitlestringY轴标题
$filenamestring/null保存文件名(null则直接输出)

高级函数配置选项

选项类型默认值说明
widthint800图表宽度(px)
heightint400图表高度(px)
titlestring'销售统计'图表标题
xTitlestring'月份'X轴标题
yTitlestring'销量'Y轴标题
colorsarray['skyblue']柱形颜色数组
filenamestring/nullnull保存文件名
showValuesbooltrue是否显示数值
gradientboolfalse是否使用渐变填充
shadowboolfalse是否添加阴影
groupedboolfalse是否为分组柱形图

5. 封装优势说明

  1. 代码复用性‌:避免重复编写相同的图表生成代码

  2. 参数标准化‌:统一参数格式,降低使用难度

  3. 错误处理‌:内置异常捕获机制

  4. 灵活性‌:通过配置选项支持多种图表样式

  5. 可扩展性‌:易于添加新的图表功能

6. 实际应用建议

  1. 可将这些函数放入单独的chart_utils.php文件中

  2. 在需要生成图表的地方包含该文件即可

  3. 对于频繁使用的配置,可以预定义配置模板:

// 预定义公司标准样式
$companyStyle = [
    'width' => 900,
    'height' => 500,
    'colors' => ['#1E88E5', '#43A047', '#F4511E'],
    'gradient' => true,
    'shadow' => true
];
// 使用时合并配置
$options = array_merge($companyStyle, [
    'title' => '季度销售报告',
    'grouped' => true
]);

通过这种封装方式,可以大大简化项目中图表生成的复杂度,提高开发效率。

标签: