QCustomPlot绘制多条曲线在不同的位置

QCustomPlot绘制多条曲线在不同的位置_第1张图片

   ui->setupUi(this);

    QCPLayoutGrid* layout = ui->customPlot->plotLayout();
    //把之前的布局清除
    layout->clear();
    //设置行间距
    layout->setRowSpacing(0);
    layout->setColumnSpacing(0);

    // 2. 准备数据
    QVector<double> x(101), y(101);
    for (int i = 0; i < 101; ++i) {
        x[i] = i / 50.0 - 1;
        y[i] = x[i] * x[i];
    }

    int count = 4;
    for (int i = 0; i < count; i++) {
        QCPAxisRect* axisRect = new QCPAxisRect(ui->customPlot);
        layout->addElement(i, 0, axisRect);
        if (i > 0 && i < count - 1) {
            axisRect->setMinimumMargins(QMargins(0, 0, 15, 0));
        }

        //拿到XY坐标轴对象
        QCPAxis* xAxis = axisRect->axis(QCPAxis::atBottom);
        QCPAxis* yAxis = axisRect->axis(QCPAxis::atLeft);
        yAxis->setLabel(QString("曲线 %1").arg(i + 1));

        //网格线不可见
        xAxis->grid()->setVisible(false);
        yAxis->grid()->setVisible(false);
    }

    QCPAxisRect* axisRect1 = qobject_cast<QCPAxisRect*>(layout->elementAt(0));
    QCPBars* volumePos = new QCPBars(axisRect1->axis(QCPAxis::atBottom), axisRect1->axis(QCPAxis::atLeft));
    volumePos->addData(x, y);
    volumePos->setPen(Qt::NoPen);
    volumePos->setBrush(QColor(100, 180, 110));

    QCPAxisRect* axisRect2 = qobject_cast<QCPAxisRect*>(layout->elementAt(1));
    QCPGraph* subGraphRandom = ui->customPlot->addGraph(axisRect2->axis(QCPAxis::atBottom), axisRect2->axis(QCPAxis::atLeft));
    subGraphRandom->addData(x, y);
    subGraphRandom->setPen(QPen(Qt::red, 4));
    //subGraphRandom->setBrush(QColor(100, 180, 110));

    ui->customPlot->replot();
    return;

你可能感兴趣的:(QT,QCustomPlot,qt)