Displaying Temperature Records with Negative Bars▲
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 &
lt;&
lt; -
52
&
lt;&
lt; -
50
&
lt;&
lt; -
45.3
&
lt;&
lt; -
37.0
&
lt;&
lt; -
25.6
&
lt;&
lt; -
8.0
&
lt;&
lt; -
6.0
&
lt;&
lt; -
11.8
&
lt;&
lt; -
19.7
&
lt;&
lt; -
32.8
&
lt;&
lt; -
43.0
&
lt;&
lt; -
48.0
;
*
high &
lt;&
lt; 11.9
&
lt;&
lt; 12.8
&
lt;&
lt; 18.5
&
lt;&
lt; 26.5
&
lt;&
lt; 32.0
&
lt;&
lt; 34.8
&
lt;&
lt; 38.2
&
lt;&
lt; 34.8
&
lt;&
lt; 29.8
&
lt;&
lt; 20.4
&
lt;&
lt; 15.1
&
lt;&
lt; 11.8
;
We create the series and append the barsets to it. The series takes ownership of the barsets.
auto
series =
new
QStackedBarSeries;
series-&
gt;append(low);
series-&
gt;append(high);
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-&
gt;addSeries(series);
chart-&
gt;setTitle("Temperature records in Celcius"
);
chart-&
gt;setAnimationOptions(QChart::
SeriesAnimations);
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;
axisX-&
gt;append(categories);
axisX-&
gt;setTitleText("Month"
);
chart-&
gt;addAxis(axisX, Qt::
AlignBottom);
auto
axisY =
new
QValueAxis;
axisY-&
gt;setRange(-
52
, 52
);
axisY-&
gt;setTitleText("Temperature [°C]"
);
chart-&
gt;addAxis(axisY, Qt::
AlignLeft);
series-&
gt;attachAxis(axisX);
series-&
gt;attachAxis(axisY);
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.
chart-&
gt;legend()-&
gt;setVisible(true
);
chart-&
gt;legend()-&
gt;setAlignment(Qt::
AlignBottom);
Finally we add the chart onto a view.
createDefaultChartView(chart);
The chart is ready to be shown.