创建水平百分比条形图
注: 这是 "带 Widgets 图库的图表"示例的一部分。
水平百分比条形图显示的是一个集合中的数据占每个类别所有集合的百分比。
创建水平百分比条形图与创建普通条形图一样,只是对于水平百分比条形图,我们使用QHorizontalPercentBarSeries api 而不是QBarSeries 。此外,在条形图中,我们使用了一种漂亮的数字算法,使 Y 轴的编号看起来更好。在百分比条形图中则不需要这样,因为 Y 轴的最大值始终是 100。
所有柱形图都以相同的方式使用柱形集。为了说明各种柱状图之间的区别,我们在示例中使用了相同的数据。条形图可视化的数据由QBarSet 实例定义。在这里,我们创建数据集,并向其中添加数据。这里使用 << 操作符追加数据。或者也可以使用 append 方法。
auto set0 = new QBarSet("Jane"); auto set1 = new QBarSet("John"); auto set2 = new QBarSet("Axel"); auto set3 = new QBarSet("Mary"); auto set4 = new QBarSet("Samantha"); *set0 << 1 << 2 << 3 << 4 << 5 << 6; *set1 << 5 << 0 << 0 << 4 << 0 << 7; *set2 << 3 << 5 << 8 << 13 << 8 << 5; *set3 << 5 << 6 << 7 << 3 << 4 << 5; *set4 << 9 << 7 << 5 << 3 << 1 << 2;
我们创建系列并将条形集添加到系列中。系列拥有条形集的所有权。系列将数据从数据集分组到类别。每组数据的第一个值归入第一个类别,第二个值归入第二个类别,等等。
auto series = new QHorizontalPercentBarSeries; series->append(set0); series->append(set1); series->append(set2); series->append(set3); series->append(set4);
在此,我们创建图表对象并添加系列。我们使用 setTitle 为图表设置标题,然后调用 setAnimationOptions(QChart::SeriesAnimations) 打开系列的动画。
auto chart = new QChart; chart->addSeries(series); chart->setTitle("Simple Horizontal Percent Bar Chart"); chart->setAnimationOptions(QChart::SeriesAnimations);
要在坐标轴上显示类别,我们需要先创建一个QBarCategoryAxis 。在这里,我们创建了一个包含类别列表的类别轴,并将其添加到图表左侧,作为 y 轴。图表拥有轴的所有权。对于 x 轴,我们使用数值轴,并将其对齐至底部。
QStringList categories {"Jan", "Feb", "Mar", "Apr", "May", "Jun"}; auto axisY = new QBarCategoryAxis; axisY->append(categories); chart->addAxis(axisY, Qt::AlignLeft); series->attachAxis(axisY); auto axisX = new QValueAxis; chart->addAxis(axisX, Qt::AlignBottom); series->attachAxis(axisX);
我们还希望显示图例。为此,我们从图表中获取图例指针,并将其设置为可见。我们还将图例对齐方式设置为Qt::AlignBottom ,从而将其置于图表底部。
chart->legend()->setVisible(true); chart->legend()->setAlignment(Qt::AlignBottom);
最后,我们将图表添加到视图中。
createDefaultChartView(chart);
© 2025 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.