轉自:https://blog.csdn.net/yxy244/article/details/100086205
官網圖例https://www.qcustomplot.com/index.php/demos/simpledemo
1 QCustomPlot* customPlot = ui->customPlot_6; 2 // 添加兩個graph 3 customPlot->addGraph(); 4 customPlot->graph(0)->setPen(QPen(Qt::blue)); // 第一條曲線顏色 5 customPlot->graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20))); // 第一條曲線和0軸圍成區域填充的顏色 6 customPlot->addGraph(); 7 customPlot->graph(1)->setPen(QPen(Qt::red)); // 第二條曲線顏色 8 // 生成數據 9 QVector<double> x(251), y0(251), y1(251); 10 for (int i=0; i<251; ++i) 11 { 12 x[i] = i; 13 y0[i] = qExp(-i/150.0)*qCos(i/10.0); // 指數衰減的cos 14 y1[i] = qExp(-i/150.0); // 衰減指數 15 } 16 // 配置右側和頂部軸顯示刻度,但不顯示標簽: 17 customPlot->xAxis2->setVisible(true); 18 customPlot->xAxis2->setTickLabels(false); 19 customPlot->yAxis2->setVisible(true); 20 customPlot->yAxis2->setTickLabels(false); 21 // 讓左邊和下邊軸與上邊和右邊同步改變范圍 22 connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange))); 23 connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange))); 24 // 設置數據點 25 customPlot->graph(0)->setData(x, y0); 26 customPlot->graph(1)->setData(x, y1); 27 // 讓范圍自行縮放,使圖0完全適合於可見區域: 28 customPlot->graph(0)->rescaleAxes(); 29 // 圖1也是一樣自動調整范圍,但只是放大范圍(如果圖1小於圖0): 30 customPlot->graph(1)->rescaleAxes(true); 31 // 允許用戶用鼠標拖動軸范圍,用鼠標滾輪縮放,點擊選擇圖形: 32 customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); 33 customPlot->replot();
(1)上下軸,左右軸范圍同步
利用rangeChanged信號傳遞軸范圍QCPRange,范圍改變時將xAxis的范圍傳給xAxis2,yAxis也是,就能實現軸范圍同步了。
connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));
(2)自動調整范圍,使數據全部可見。
調用rescaleAxes (bool onlyEnlarge = false)重新調整與此繪圖表關聯的鍵和值軸,以顯示所有的數據
onlyEnlarge 默認false,表示范圍可以縮小放大,如果為true表示只能放大,而不會縮小范圍。
例如曲線:
調用 customPlot->graph(0)->rescaleAxes();后范圍被縮小了,曲線正好占滿整個區域,但是調用customPlot->graph(0)->rescaleAxes(true)就不會有變化,因為區域不會縮小。
利用這點可以通過多次調用rescaleaxis來完整地顯示多個graph的數據。讓graph(0)自動縮放rescaleAxes(),在graph(0)范圍的基礎上rescaleAxes(true)只會擴大范圍或不變而不縮小,這樣最終能夠顯示graph(n)所有的數據
1 // 讓范圍自行縮放,使圖0完全適合於可見區域: 2 customPlot->graph(0)->rescaleAxes(); 3 // 圖1也是一樣自動調整范圍,但只是放大或不變范圍 4 customPlot->graph(1)->rescaleAxes(true); 5 // 圖2也是一樣自動調整范圍,但只是放大或不變范圍 6 customPlot->graph(2)->rescaleAxes(true); 7 // 圖3也是一樣自動調整范圍,但只是放大或不變范圍 8 customPlot->graph(2)->rescaleAxes(true); 9 。。。