如何正确绘制日期为 x 轴的散点图?

时间:2021-04-20 22:15:14

标签: php phpspreadsheet

我得到了一个循环绘制 N 个图表的代码,用于使用以前在工作表中设置的数据,如下所示:

foreach ($component->getVariablesData() as $variable) { 
    //$variable = ['table_name_1', 'table_name_2', 'worksheet_name', 'limit', array_data]
    //array_data = [[data_table_2, data_table_1], [data_table_2, data_table_1], [data_table_2, data_table_1], ...]
    $sheet = $spreadsheet->createSheet();
    $sheet->setTitle($variable[2]);
    $sheet->setCellValue('A1', $variable[0]);
    $sheet->setCellValue('B1', $variable[1]);
    for ($i = 0; $i<count($variable[4]); $i++) {
        $sheet->setCellValue('B' . (string)($i + 2), $variable[4][$i][0]);
        $sheet->setCellValue('A' . (string)($i + 2), \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($variable[4][$i][1]));
        $sheet->getStyle('A' . (string)($i + 2))->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
    }
    //======================================================
    $dataSeriesLabels = [
        new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, '\''.$variable[1].'\'!$B$1', null, 1), // Table name 2
    ];
    $xAxisTickValues = [
        new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, '\''.$variable[1].'\'!$A$2:$A$'.(string)($i - 1), null, count($variable[4])), //Set the range of x Axis previouly load to the worksheet, this are the dates
    ];
    $dataSeriesValues = [
        new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, '\''.$variable[1].'\'!$B$2:$B$'.(string)($i - 1), null, count($variable[4])), //Set the range of data previously load to the worksheet, this are the data point
    ];
    // Build the dataseries
    $series = new DataSeries(
        DataSeries::TYPE_SCATTERCHART, // plotType
        null, // plotGrouping (Scatter charts don't have any grouping)
        range(0, count($dataSeriesValues) - 1), // plotOrder
        $dataSeriesLabels, // plotLabel
        $xAxisTickValues, // plotCategory
        $dataSeriesValues, // plotValues
        null, // plotDirection
        null, // smooth line
        DataSeries::STYLE_LINEMARKER  // plotStyle
    );

    // Set the series in the plot area
    $plotArea = new PlotArea(null, [$series]);
    $title = new Title('Test Scatter Chart '.$variable[1]);
    // Create the chart
    $chart = new Chart(
        'chart'.$variable[1], // name
        $title, // title
        null, // legend
        $plotArea, // plotArea
        true, // plotVisibleOnly
        DataSeries::EMPTY_AS_GAP, // displayBlanksAs
        null, // xAxisLabel
        null  // yAxisLabel
    );
    $sheet->addChart($chart);
}

问题是我得到了这样的东西:

Result of previous code

我想画一个这样的图表:

Desired result

我已经尝试设置 xAxisLabel 但只是日期下的标题标签所以它不起作用,我不知道为什么我的 x 轴是隐藏的,为什么我不能在我的情节中绘制垂直线,我在想因为是日期值,但我不确定。

预先感谢您的帮助。

0 个答案:

没有答案