使用phpspreadsheet创建组合图表并设置次坐标轴和x轴坐标间隔
本文介绍如何使用PhpSpreadsheet库创建组合图表,并设置次坐标轴以及X轴坐标间隔。

步骤:
<code class="php">$chart = new \PhpOffice\PhpSpreadsheet\Chart\Chart();</code>
创建数据系列,并指定哪些系列使用次坐标轴。 以下代码示例展示了如何添加一个使用百分比值(次坐标轴)和一个使用数值(主坐标轴)的数据系列。
立即学习“PHP免费学习笔记(深入)”;
<code class="php">$dataSeriesValues = [
new \PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues('Number', 'Worksheet!$A$1:$A$5'), // 主坐标轴数据
new \PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues('Percentage', 'Worksheet!$B$1:$B$5') // 次坐标轴数据
];
$xAxisTickValues = [
new \PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues('String', 'Worksheet!$C$1:$C$5') // X轴分类数据
];
$series = new \PhpOffice\PhpSpreadsheet\Chart\Series(
$dataSeriesValues,
$xAxisTickValues
);
$series->setPlotDirection(\PhpOffice\PhpSpreadsheet\Chart\Series::PLOT_DIRECTION_HORIZONTAL); // 指定次坐标轴
$chart->addSeries($series);
$series = new \PhpOffice\PhpSpreadsheet\Chart\Series(
new \PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues('Number', 'Worksheet!$A$1:$A$5') // 主坐标轴数据
);
$series->setPlotDirection(\PhpOffice\PhpSpreadsheet\Chart\Series::PLOT_DIRECTION_VERTICAL); // 指定主坐标轴
$chart->addSeries($series);</code><code class="php">$layoutSecondaryAxes = new \PhpOffice\PhpSpreadsheet\Chart\Layout\Layout(); $layoutSecondaryAxes->setShowAxis(true); $yAxisSecondary = new \PhpOffice\PhpSpreadsheet\Chart\Axis(); $yAxisSecondary->setLayout($layoutSecondaryAxes); $chart->addAxis($yAxisSecondary, \PhpOffice\PhpSpreadsheet\Chart\Axis::VERTICAL, $layoutSecondaryAxes); // 添加次坐标轴</code>
<code class="php">$layoutXAxis = new \PhpOffice\PhpSpreadsheet\Chart\Layout\Layout(); $layoutXAxis->setTickValFrequency(1); // 设置X轴坐标间隔为1 $xAxis = new \PhpOffice\PhpSpreadsheet\Chart\Axis(); $xAxis->setLayout($layoutXAxis); $chart->addAxis($xAxis, \PhpOffice\PhpSpreadsheet\Chart\Axis::HORIZONTAL); // 添加X轴</code>
记住替换 'Worksheet!' 为你的工作表名称。 通过调整 setTickValFrequency() 的值,可以控制X轴坐标的间隔。 这个例子中设置为1,表示每个数据点都显示在X轴上。
最后,将图表添加到工作表中:
<code class="php">$worksheet->addChart($chart);</code>
通过以上步骤,您可以成功地使用PhpSpreadsheet创建具有次坐标轴和自定义X轴坐标间隔的组合图表。 请确保您已正确安装并包含PhpSpreadsheet库。
以上就是如何用PhpSpreadsheet设置组合图表的次坐标轴和X轴坐标间隔?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号