示例qcustomplot多条曲线多个Y轴
时间: 2023-05-29 14:04:40 浏览: 1733
在QCustomPlot中,可以使用addGraph()函数添加多条曲线,使用QCPAxisRect类创建多个Y轴。
以下是一个示例代码:
```cpp
#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->setGeometry(50, 50, 600, 400);
//添加多个Y轴
QCPAxisRect *axisRect1 = new QCPAxisRect(customPlot);
customPlot->plotLayout()->addElement(0, 0, axisRect1);
axisRect1->setupFullAxesBox(true);
axisRect1->axis(QCPAxis::atLeft)->setLabel("y1");
QCPAxisRect *axisRect2 = new QCPAxisRect(customPlot);
customPlot->plotLayout()->addElement(0, 1, axisRect2);
axisRect2->setupFullAxesBox(true);
axisRect2->axis(QCPAxis::atLeft)->setLabel("y2");
//添加曲线
QVector<double> x(101), y0(101), y1(101), y2(101), y3(101);
for (int i=0; i<101; i++)
{
x[i] = i/50.0-1;
y0[i] = qExp(-x[i]*x[i]*2);
y1[i] = qSin(x[i]*3);
y2[i] = qCos(x[i]*3);
y3[i] = qTan(x[i]*3);
}
QCPGraph *graph0 = customPlot->addGraph(axisRect1->axis(QCPAxis::atBottom), axisRect1->axis(QCPAxis::atLeft));
graph0->setData(x, y0);
graph0->setPen(QPen(Qt::blue));
QCPGraph *graph1 = customPlot->addGraph(axisRect2->axis(QCPAxis::atBottom), axisRect2->axis(QCPAxis::atLeft));
graph1->setData(x, y1);
graph1->setPen(QPen(Qt::red));
QCPGraph *graph2 = customPlot->addGraph(axisRect2->axis(QCPAxis::atBottom), axisRect2->axis(QCPAxis::atLeft, 1));
graph2->setData(x, y2);
graph2->setPen(QPen(Qt::green));
QCPGraph *graph3 = customPlot->addGraph(axisRect2->axis(QCPAxis::atBottom), axisRect2->axis(QCPAxis::atLeft, 2));
graph3->setData(x, y3);
graph3->setPen(QPen(Qt::black));
//设置坐标轴范围
axisRect1->axis(QCPAxis::atBottom)->setRange(-1, 1);
axisRect1->axis(QCPAxis::atLeft)->setRange(0, 1);
axisRect2->axis(QCPAxis::atBottom)->setRange(-1, 1);
axisRect2->axis(QCPAxis::atLeft)->setRange(-1, 1);
axisRect2->axis(QCPAxis::atLeft, 1)->setRange(-1, 1);
axisRect2->axis(QCPAxis::atLeft, 2)->setRange(-10, 10);
//添加图例
customPlot->legend->setVisible(true);
customPlot->legend->setFont(QFont("Helvetica", 9));
customPlot->legend->setBrush(QBrush(QColor(255,255,255,230)));
//显示图形
customPlot->replot();
}
MainWindow::~MainWindow()
{
delete ui;
}
```
该代码会在窗口中显示一个包含多条曲线和多个Y轴的QCustomPlot对象,每个Y轴对应一条曲线。其中,QCPAxisRect类用于创建多个Y轴,addGraph()函数用于添加多条曲线,setData()函数用于设置曲线的数据,setPen()函数用于设置曲线颜色,axis()函数用于获取坐标轴对象,setRange()函数用于设置坐标轴范围,legend类用于添加图例。