qcustomplot绘制柱状图
时间: 2023-10-01 13:03:39 浏览: 354
qcustomplot 绘制 饼状图和 柱状图
使用QCustomPlot绘制柱状图的具体步骤如下:
1. 创建QCustomPlot对象并设置其大小和标题。
```
QCustomPlot *customPlot = new QCustomPlot(this);
customPlot->setFixedSize(500, 300);
customPlot->plotLayout()->insertRow(0);
customPlot->plotLayout()->addElement(0, 0, new QCPTextElement(customPlot, "柱状图", QFont("sans", 12, QFont::Bold)));
```
2. 创建QCPBars对象并设置其数据和颜色。
```
QCPBars *bars = new QCPBars(customPlot->xAxis, customPlot->yAxis);
bars->setData(x, y); // x和y分别为 QVector<double> 类型的数据
bars->setBrush(QColor(255, 131, 0));
```
3. 设置X轴和Y轴的范围和标签。
```
customPlot->xAxis->setRange(0, x.size());
customPlot->xAxis->setTickVectorLabels(labels); // labels为 QVector<QString> 类型的标签
customPlot->yAxis->setRange(0, 10);
customPlot->xAxis->setLabel("X轴标签");
customPlot->yAxis->setLabel("Y轴标签");
```
4. 更新图表。
```
customPlot->replot();
```
完整的代码示例:
```
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qcustomplot.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 创建QCustomPlot对象并设置其大小和标题
QCustomPlot *customPlot = new QCustomPlot(this);
customPlot->setFixedSize(500, 300);
customPlot->plotLayout()->insertRow(0);
customPlot->plotLayout()->addElement(0, 0, new QCPTextElement(customPlot, "柱状图", QFont("sans", 12, QFont::Bold)));
// 设置数据
QVector<double> x = QVector<double>() << 1 << 2 << 3 << 4 << 5;
QVector<double> y = QVector<double>() << 2 << 4 << 6 << 8 << 10;
QVector<QString> labels = QVector<QString>() << "A" << "B" << "C" << "D" << "E";
// 创建QCPBars对象并设置其数据和颜色
QCPBars *bars = new QCPBars(customPlot->xAxis, customPlot->yAxis);
bars->setData(x, y);
bars->setBrush(QColor(255, 131, 0));
// 设置X轴和Y轴的范围和标签
customPlot->xAxis->setRange(0, x.size());
customPlot->xAxis->setTickVectorLabels(labels);
customPlot->yAxis->setRange(0, 10);
customPlot->xAxis->setLabel("X轴标签");
customPlot->yAxis->setLabel("Y轴标签");
// 更新图表
customPlot->replot();
}
MainWindow::~MainWindow()
{
delete ui;
}
```
阅读全文