QCustomPlot_PyQt6 QCPAxis
时间: 2025-09-01 18:54:25 AIGC 浏览: 14
<think>
我们之前讨论了QCPItemPosition,现在用户询问的是QCPAxis的使用方法和相关信息。
注意:用户提到“参考站内引用”,但实际没有提供具体引用内容,因此我们主要基于QCustomPlot的官方文档和常见用法来回答。
我们将介绍QCPAxis的核心功能、使用方法、示例代码和注意事项。
</think>
### QCPAxis in QCustomPlot_PyQt6 详解
QCPAxis 是 QCustomPlot 中管理坐标轴的核心组件,负责数据可视化中的坐标映射、刻度标记和网格显示。以下是其核心功能和使用方法:
#### 一、核心功能特性
1. **坐标映射机制**
- 数据坐标 ⇌ 像素坐标双向转换:
$$ \text{pixel} = \text{axis} \rightarrow \text{coordToPixel(value)} $$
$$ \text{value} = \text{axis} \rightarrow \text{pixelToCoord(pixel)} $$
支持线性($linear$)和对数($logarithmic$)两种缩放模式[^1]。
2. **多层刻度系统**
```mermaid
graph TD
A[主刻度] --> B[刻度标签]
A --> C[主网格线]
D[次刻度] --> E[次网格线]
```
3. **范围控制**
- 自动缩放:`setRange(QCPRange(min, max))`
- 手动固定:`setRange(0, 100)`
- 动态响应:`rescale()` 自动适配数据
#### 二、基础使用方法
```python
from PyQt6.QtWidgets import QApplication
import sys
import qcustomplot as qcp
app = QApplication(sys.argv)
plot = qcp.QCustomPlot()
# 创建坐标轴(默认已包含xAxis/yAxis)
x_axis = plot.xAxis
y_axis = plot.yAxis
# 设置轴属性
x_axis.setLabel("时间(s)") # 轴标题
x_axis.setRange(0, 10) # 显示范围
y_axis.setLabel("温度(℃)", font=qcp.QFont("Arial", 12))
# 配置刻度
x_axis.setTickLength(0, 5) # 主刻度长0,次刻度长5
y_axis.setTicks(True) # 显示主刻度
y_axis.setTickLabels(True) # 显示刻度标签
# 添加数据
graph = plot.addGraph()
graph.setData([1,2,3,4], [10,25,8,32])
plot.rescaleAxes() # 自动调整坐标范围
plot.replot()
app.exec()
```
#### 三、高级配置技巧
1. **自定义刻度标签**
```python
# 时间轴特殊格式化
x_axis.setTickLabelType(qcp.QCPAxis.ltDateTime)
x_axis.setDateTimeFormat("hh:mm")
# 数值轴自定义文本
def custom_label(tick):
return f"{tick:.1f}°"
y_axis.setTickLabelFormatter(custom_label)
```
2. **多轴系统**
```python
# 创建右侧Y轴
y2_axis = qcp.QCPAxis(plot.axisRect(), qcp.QCPAxis.atRight)
plot.axisRect().addAxis(qcp.QCPAxis.atRight, y2_axis)
y2_axis.setLabel("湿度(%)")
# 绑定到特定图表
plot.graph(0).valueAxis = y2_axis
```
3. **动态范围联动**
```python
# 实现Y轴同步缩放
def sync_y_ranges():
y2_axis.setRange(y_axis.range())
y_axis.rangeChanged.connect(sync_y_ranges)
```
#### 四、关键方法说明
| **方法** | **参数** | **功能** | **数学关系** |
|----------|----------|----------|--------------|
| `setRange(lower, upper)` | 浮点数 | 设置显示范围 | $[lower, upper]$ |
| `coordToPixel(value)` | 数据值 | 值→像素 | $pix = \frac{value - min}{max - min} \times width$ |
| `setScaleType(type)` | Linear/Log | 缩放类型 | $log: pix \propto \log_{10}(value)$ |
| `setScaleRatio(refAxis, ratio)` | 参考轴, 比例 | 轴比例同步 | $\frac{range_{this}}{range_{ref}} = ratio$ |
#### 五、典型应用场景
1. **实时数据更新**
```python
def update_data():
new_x = time.time()
new_y = sensor.read()
graph.addData(new_x, new_y)
x_axis.setRange(new_x-10, new_x) # 显示最近10秒
plot.replot()
timer = qcp.QTimer()
timer.timeout.connect(update_data)
timer.start(1000) # 每秒更新
```
2. **对数坐标**
```python
# 设置对数坐标轴
y_axis.setScaleType(qcp.QCPAxis.stLogarithmic)
y_axis.setNumberPrecision(2) # 对数刻度精度
y_axis.setRange(1e-2, 1e3) # 10^{-2}到10^{3}
```
3. **自定义网格样式**
```python
# 主网格线
plot.xAxis.grid().setPen(qcp.QPen(qcp.Qt.gray, 1, qcp.Qt.DotLine))
# 次网格线
plot.yAxis.grid().setSubGridVisible(True)
plot.yAxis.grid().setSubGridPen(qcp.QPen(qcp.Qt.lightGray, 1, qcp.Qt.DotLine))
```
#### 六、注意事项
1. **性能优化**
- 大数据集时禁用自动计算:
```python
plt.setAutoAddPlottableToLegend(False)
plt.setNotAntialiasedElements(qcp.QCP.AE_ALL)
```
- 固定刻度数量避免重算:
```python
x_axis.setAutoTickCount(10) # 固定10个主刻度
```
2. **坐标转换公式**
对于线性坐标系:
$$
\text{pixelX} = \text{axisRectLeft} + \frac{\text{value} - \text{axisMin}}{\text{axisMax} - \text{axisMin}} \times \text{axisRectWidth}
$$
3. **内存管理**
```python
# 正确移除坐标轴
plot.axisRect().removeAxis(y2_axis)
del y2_axis
```
> 提示:使用 `axisRect().setupFullAxesBox(True)` 可快速创建四周边框轴系统[^2]。
阅读全文