使用多个坐标轴

注意:这是 “带小部件的图表”示例库的一部分。

显示两个带有三个坐标轴的折线图的屏幕截图

创建 QChart 实例,隐藏图表的图例,并设置其标题。

auto chart = new QChart;
chart->legend()->hide();
chart->setTitle("Multiple Vertical Axes in Chart");

创建一个 QValueAxis 实例,该实例将作为两个数据系列共用的水平轴,并将其添加到图表底部。该轴可被多个数据系列共享,但每个数据系列仅能拥有一个垂直轴和一个水平轴。

auto axisX = new QValueAxis;
axisX->setTickCount(10);
chart->addAxis(axisX, Qt::AlignBottom);

创建第一个数据系列,并向其中添加数据。 最后,将数据系列添加到图表中。为其实例化专属的 Y 轴,并将其添加到图表中。然后将公共的 X 轴和该数据系列专属的 Y 轴分别关联到该系列。在本示例中,轴线的颜色设置为与该数据系列的颜色相同,以便区分哪个轴与哪个数据系列相关联。

auto series = new QSplineSeries;
*series << QPointF(1, 5) << QPointF(3.5, 18) << QPointF(4.8, 7.5) << QPointF(10, 2.5);
chart->addSeries(series);

auto axisY = new QValueAxis;
axisY->setLinePenColor(series->pen().color());

chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisX);
series->attachAxis(axisY);

以同样的方式准备另一个数据系列。这次使用不同的坐标轴类型。此外,网格线的颜色也设置为与该数据系列的颜色相同。

series = new QSplineSeries;
*series << QPointF(1, 0.5) << QPointF(1.5, 4.5) << QPointF(2.4, 2.5) << QPointF(4.3, 12.5)
        << QPointF(5.2, 3.5) << QPointF(7.4, 16.5) << QPointF(8.3, 7.5) << QPointF(10, 17);
chart->addSeries(series);

auto axisY3 = new QCategoryAxis;
axisY3->append("Low", 5);
axisY3->append("Medium", 12);
axisY3->append("High", 17);
axisY3->setLinePenColor(series->pen().color());
axisY3->setGridLinePen((series->pen()));

chart->addAxis(axisY3, Qt::AlignRight);
series->attachAxis(axisX);
series->attachAxis(axisY3);

创建一个以 QChart 为参数的 QChartView 对象。

createDefaultChartView(chart);

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.