Displaying Temperature Records with Negative Bars

Note: This is part of the Charts with Widgets Gallery example. For our example we use temperature data.

First we create two barsets and append the data to them. One set represents the minimum temperatures and another the maximum temperatures.

auto low = new QBarSet("Min");
auto high = new QBarSet("Max");

*low << -52 << -50 << -45.3 << -37.0 << -25.6 << -8.0
     << -6.0 << -11.8 << -19.7 << -32.8 << -43.0 << -48.0;
*high << 11.9 << 12.8 << 18.5 << 26.5 << 32.0 << 34.8
      << 38.2 << 34.8 << 29.8 << 20.4 << 15.1 << 11.8;

We create the series and append the barsets to it. The series takes ownership of the barsets.

auto series = new QStackedBarSeries;

Here we create the chart object and add the series to it. We set the title for the chart with setTitle, and then turn on animations of the series by calling setAnimationOptions(QChart::SeriesAnimations)

auto chart = new QChart;
chart->setTitle("Temperature records in Celcius");

To have the categories displayed on an axis, we need to create a QBarCategoryAxis. Here we create a category axis with a list of categories and add it to the chart aligned to bottom, acting as the x-axis. The chart takes ownership of the axis. For y-axis we use a value axis, aligned to the left-hand side. We change the range for the y-axis, as this gives nicer results than with autoscaling.

QStringList categories = {
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"

auto axisX = new QBarCategoryAxis;
chart->addAxis(axisX, Qt::AlignBottom);
auto axisY = new QValueAxis;
axisY->setRange(-52, 52);
axisY->setTitleText("Temperature [&deg;C]");
chart->addAxis(axisY, Qt::AlignLeft);

We also want to show the legend. To do so, we get the legend pointer from the chart and set it to visible. We also place the legend to the bottom of the chart by setting its alignment to Qt::AlignBottom.


Finally we add the chart onto a view.


The chart is ready to be shown.

© 2024 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.