박스 앤 위스커 차트 만들기
참고: 이 내용은 ‘위젯이 포함된 차트 갤러리’ 예제의 일부입니다.
이 예제에서는 파일에서 비연속 데이터를 읽어들이고, 데이터를 정리하며, 박스-위스커 차트 작성에 필요한 중앙값을 구하는 방법도 보여줍니다.

두 회사의 주가 편차를 보여주기 위해, 먼저 월별 데이터를 처리할 두 개의 QBoxPlotSeries를 생성합니다.
auto acmeSeries = new QBoxPlotSeries;
acmeSeries->setName("Acme Ltd");
auto boxWhiskSeries = new QBoxPlotSeries;
boxWhiskSeries->setName("BoxWhisk Inc");QFile 클래스는 비연속 데이터가 저장된 텍스트 파일을 여는 데 사용됩니다. BoxDataReader는 텍스트 파일을 읽고 데이터에서 극값 및 중앙값을 찾는 데 사용되는 보조 클래스입니다. BoxDataReader에 대해서는 나중에 더 자세히 설명하겠습니다. readBox 메서드는 값을 읽어와 호출자에게 반환하는 QBoxSet 항목에 설정합니다. 반환된 QBoxSet 항목은 시리즈에 추가됩니다.
QFile acmeData(":boxplot_a");
const QString errorTemplate = QStringLiteral("Failed to load '%1' file.");
if (!acmeData.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_loadError = errorTemplate.arg(acmeData.fileName());
return false;
}
BoxPlotDataReader dataReader(&acmeData);
while (!dataReader.atEnd()) {
QBoxSet *set = dataReader.readBox();
if (set)
acmeSeries->append(set);
}이 섹션에서는 두 번째 회사의 데이터를 읽기 위해 두 번째 파일을 엽니다.
QFile boxwhiskData(":boxplot_b");
if (!boxwhiskData.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_loadError = errorTemplate.arg(acmeData.fileName());
return false;
}
dataReader.readFile(&boxwhiskData);
while (!dataReader.atEnd()) {
QBoxSet *set = dataReader.readBox();
if (set)
boxWhiskSeries->append(set);
}이 코드 스니펫에서는 새로운 QChart 인스턴스가 생성되고, 이전에 생성된 시리즈가 여기에 추가됩니다. 또한 제목이 정의되고 애니메이션은 SeriesAnimation으로 설정됩니다.
auto chart = new QChart;
chart->addSeries(acmeSeries);
chart->addSeries(boxWhiskSeries);
chart->setTitle("Acme Ltd. and BoxWhisk Inc. share deviation in 2012");
chart->setAnimationOptions(QChart::SeriesAnimations);여기서는 차트에 프레젠테이션을 위한 기본 축을 생성하도록 요청합니다. 또한 차트에서 축 포인터를 조회한 후 해당 축의 최소값과 최대값을 설정하여 수직축의 범위를 지정합니다.
chart->createDefaultAxes();
chart->axes(Qt::Vertical).first()->setMin(15.0);
chart->axes(Qt::Horizontal).first()->setMax(34.0);이 섹션에서는 범례를 표시하도록 설정하고 차트 하단에 배치합니다.
chart->legend()->setVisible(true);
chart->legend()->setAlignment(Qt::AlignBottom);마지막으로 차트를 뷰에 추가합니다. 또한 차트 뷰에 대해 앤티앨리어싱을 활성화합니다.
createDefaultChartView(chart);이제 차트를 표시할 준비가 되었습니다.
여기서는 readBox 메서드에 대해 자세히 설명합니다.
먼저 파일에서 한 줄을 읽어들여, #으로 시작하는 줄은 주석 줄로 간주하여 제외합니다.
QString line = m_textStream.readLine();
if (line.startsWith("#"))
return nullptr;이 파일에서 데이터는 숫자, 공백, 숫자 또는 공백 순으로 배열되어 있습니다. 이 코드 조각에서는 줄을 단일 숫자 문자열로 분할하여 ` QStringList`에 저장합니다.
QStringList strList = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);sortedList는 숫자를 연속적인 순서로 저장하며, 이 코드 조각에서는 그 방법을 보여줍니다. 먼저 sortedList를 비우고, strList에서 숫자를 읽어와 double 형식으로 sortedList에 저장합니다. qSort 메서드는 sortedList를 가장 작은 숫자부터 시작하여 연속적인 순서로 정렬합니다.
m_sortedList.clear();
for (int i = 1; i < strList.count(); i++)
m_sortedList.append(strList.at(i).toDouble());
std::sort(m_sortedList.begin(), m_sortedList.end());아래에는 연속된 데이터에서 극값과 중앙값을 선택하는 방법을 보여주는 코드 예제가 있습니다. 먼저 새로운 QBoxSet이 생성됩니다. 하한값과 상한값은 선택하기 간단합니다. 이들은 단순히 sortedList의 첫 번째와 마지막 항목입니다. 중앙값의 경우, 나중에 설명할 findMedian 헬퍼 메서드를 사용합니다. 상위 절반의 중앙값을 구할 때는 숫자의 개수가 짝수인지 홀수인지에 따라 시작 번호를 조정해야 합니다. 하위 절반의 끝 번호는 정수 반올림에 따라 자연스럽게 결정됩니다.
auto box = new QBoxSet(strList.first());
box->setValue(QBoxSet::LowerExtreme, m_sortedList.first());
box->setValue(QBoxSet::UpperExtreme, m_sortedList.last());
box->setValue(QBoxSet::Median, findMedian(0, count));
box->setValue(QBoxSet::LowerQuartile, findMedian(0, count / 2));
box->setValue(QBoxSet::UpperQuartile, findMedian(count / 2 + (count % 2), count));아래는 findMedian 메서드의 코드 예시입니다. 숫자의 개수가 홀수일 경우 중간에 있는 숫자를 선택합니다. 숫자의 개수가 짝수일 경우 중간에 있는 두 개의 숫자를 선택하여 평균값을 계산합니다.
© 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.