PhpSpreadsheet导出组合图表:如何设置次坐标轴和X轴区间?

phpspreadsheet导出组合图表:如何设置次坐标轴和x轴区间?

使用PhpSpreadsheet创建组合图表:自定义次坐标轴和X轴范围

本文介绍如何在PhpSpreadsheet中创建组合图表时,自定义次坐标轴和X轴的显示范围。 以下代码示例适用于PhpSpreadsheet v1.20及以上版本。

一、设置次坐标轴

以下代码演示如何添加一个新的次坐标轴到图表中:

立即学习PHP免费学习笔记(深入)”;

// 创建一个新的PhpSpreadsheet工作簿
$spreadsheet = new PhpOfficePhpSpreadsheetSpreadsheet();

// ... (此处省略其他图表设置代码) ...

// 创建一个新的次坐标轴
$yAxisSecondary = new PhpOfficePhpSpreadsheetChartAxisValue(PhpOfficePhpSpreadsheetChartAxisValue::VERTICAL);

// 将次坐标轴添加到图表
$chart->addAxis($yAxisSecondary);

// ... (此处省略其他图表设置代码) ...
登录后复制

这段代码创建了一个垂直方向的次坐标轴,并将其添加到图表中。您可以根据需要调整$yAxisSecondary的属性来修改次坐标轴的显示方式。

二、设置X轴区间

以下代码演示如何设置X轴的显示范围,并使用日期作为X轴标签:

// ... (此处省略其他图表设置代码) ...

// 设置X轴为日期轴
$xAxis = $chart->getXAxis();
$xAxis->getValues()->setDateAxis();

// 设置日期范围 (例如,从2024年1月1日到2024年12月31日)
$startDate = new DateTime('2024-01-01');
$endDate = new DateTime('2024-12-31');

$xAxis->getTick()->getMajor()->setTimeUnit(PhpOfficePhpSpreadsheetChartAxisTick::TIME_UNIT_DAY); // 设置时间单位为天
$xAxis->getTick()->getMajor()->setSourceDateTimeZone(new DateTimeZone('UTC'));
$xAxis->getTick()->getMajor()->setScaling(PhpOfficePhpSpreadsheetChartAxisTick::SCALING_DATE);
$xAxis->getTick()->getMajor()->setSourceDataType(PhpOfficePhpSpreadsheetChartAxisTick::SOURCE_TYPE_DATETIME);

$dateRange = new PhpOfficePhpSpreadsheetChartDataSeriesDataSeriesValues(
    PhpOfficePhpSpreadsheetChartDataSeriesDataSeriesValues::TYPE_DATE,
    'PHPRange',
    [
        $startDate->format('d-m-Y'),
        $endDate->format('d-m-Y')
    ]
);


$xAxis->getTitle()->setLabelText('日期'); // 设置X轴标题
$xAxis->getTitle()->getText()->getFont()->setSize(14); // 设置X轴标题字体大小

$chart->addSeriesValues($dateRange, $xAxis);

// ... (此处省略其他图表设置代码) ...
登录后复制

这段代码设置X轴为日期轴,并指定了日期范围。您可以根据需要修改$startDate和$endDate来调整日期范围,以及修改时间单位(例如TIME_UNIT_MONTH为月)。 请确保您的数据与设置的日期范围相匹配。

请注意,这些代码片段需要包含必要的use语句来导入相应的PhpSpreadsheet类。 完整的代码需要根据您的具体数据和图表类型进行调整。

以上就是PhpSpreadsheet导出组合图表:如何设置次坐标轴和X轴区间?的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1231011.html

发表回复

Your email address will not be published. Required fields are marked *