QCPAxis *yAxis = ui->customPlot->yAxis; double minY = std::numeric_limits<double>::max(); double maxY = std::numeric_limits<double>::min(); for (int i = 0; i < ui->customPlot->graphCount(); i++) { QCPGraph *graph = ui->customPlot->graph(i); if (graph->dataCount() == 0) { continue; } QCPGraphDataContainer::const_iterator it = graph->data().constBegin(); for (; it != graph->data().constEnd(); ++it) { double value = it->value; if (value < minY) { minY = value; } if (value > maxY) { maxY = value; } } } double range = qMax(qAbs(minY), qAbs(maxY)) * 2; double center = (minY + maxY) / 2; yAxis->setRange(center - range, center + range); 多条y轴,不是所有曲线共用y轴
时间: 2024-03-08 14:46:35 浏览: 83
如果多条曲线不是共用一个y轴,那么你需要对每个y轴分别进行自适应范围的计算和设置。
具体步骤如下:
1. 获取所有y轴的指针,可以通过QCustomPlot::axisRect()的成员函数axis()来获取。
```cpp
QList<QCPAxis*> yAxisList;
for (int i = 0; i < ui->customPlot->axisRectCount(); i++) {
QCPAxisRect *axisRect = ui->customPlot->axisRect(i);
QCPAxis *yAxis = axisRect->axis(QCPAxis::atLeft);
if (yAxis != nullptr) {
yAxisList.append(yAxis);
}
}
```
2. 遍历每个y轴对应的曲线,获取最小值和最大值。
```cpp
double minY = std::numeric_limits<double>::max();
double maxY = std::numeric_limits<double>::min();
for (int i = 0; i < yAxisList.length(); i++) {
QCPAxis *yAxis = yAxisList[i];
minY = std::numeric_limits<double>::max();
maxY = std::numeric_limits<double>::min();
for (int j = 0; j < ui->customPlot->graphCount(); j++) {
QCPGraph *graph = ui->customPlot->graph(j);
if (graph->dataCount() == 0) {
continue;
}
if (graph->valueAxis() != yAxis) {
continue;
}
QCPGraphDataContainer::const_iterator it = graph->data().constBegin();
for (; it != graph->data().constEnd(); ++it) {
double value = it->value;
if (value < minY) {
minY = value;
}
if (value > maxY) {
maxY = value;
}
}
}
}
```
3. 计算自适应的范围,并设置每个y轴的范围。
```cpp
double range = qMax(qAbs(minY), qAbs(maxY)) * 2;
double center = (minY + maxY) / 2;
for (int i = 0; i < yAxisList.length(); i++) {
QCPAxis *yAxis = yAxisList[i];
yAxis->setRange(center - range, center + range);
}
```
完整代码示例:
```cpp
QList<QCPAxis*> yAxisList;
for (int i = 0; i < ui->customPlot->axisRectCount(); i++) {
QCPAxisRect *axisRect = ui->customPlot->axisRect(i);
QCPAxis *yAxis = axisRect->axis(QCPAxis::atLeft);
if (yAxis != nullptr) {
yAxisList.append(yAxis);
}
}
for (int i = 0; i < yAxisList.length(); i++) {
QCPAxis *yAxis = yAxisList[i];
double minY = std::numeric_limits<double>::max();
double maxY = std::numeric_limits<double>::min();
for (int j = 0; j < ui->customPlot->graphCount(); j++) {
QCPGraph *graph = ui->customPlot->graph(j);
if (graph->dataCount() == 0) {
continue;
}
if (graph->valueAxis() != yAxis) {
continue;
}
QCPGraphDataContainer::const_iterator it = graph->data().constBegin();
for (; it != graph->data().constEnd(); ++it) {
double value = it->value;
if (value < minY) {
minY = value;
}
if (value > maxY) {
maxY = value;
}
}
}
double range = qMax(qAbs(minY), qAbs(maxY)) * 2;
double center = (minY + maxY) / 2;
yAxis->setRange(center - range, center + range);
}
```
阅读全文