QCustomPlot 多曲线,y轴自适应为,最小值的两倍,最大值的两倍
时间: 2024-03-08 14:46:32 浏览: 241
要实现多曲线的y轴自适应,范围为最小值的两倍到最大值的两倍,可以按照以下步骤进行:
1. 获取y轴指针。
```cpp
QCPAxis *yAxis = ui->customPlot->yAxis;
```
2. 遍历所有曲线,获取最小值和最大值。
```cpp
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;
}
}
}
```
3. 计算自适应的范围,并设置y轴范围。
```cpp
double range = qMax(qAbs(minY), qAbs(maxY)) * 2;
double center = (minY + maxY) / 2;
yAxis->setRange(center - range, center + range);
```
完整代码示例:
```cpp
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);
```
阅读全文