📜  PyQtGraph - 将光标设置为散点图(1)

📅  最后修改于: 2023-12-03 15:04:01.174000             🧑  作者: Mango

PyQtGraph - 将光标设置为散点图

在数据可视化中,经常需要将光标(或者鼠标)的位置与数据进行关联。 PyQtGraph 是 Python 的一个数据可视化库,支持将光标设置为散点图,非常方便。

安装 PyQtGraph
pip install pyqtgraph
绘制散点图
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui

# 创建窗口和图形区域
app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="My plot")
win.resize(1000, 600)
win.setWindowTitle('pyqtgraph example: scatter')
graphWidget = win.addPlot(title="Scatter plot")

# 准备数据
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 5, 7, 8, 1, 2, 4, 6, 9, 3]

# 绘制散点图
scatter = pg.ScatterPlotItem(x=x, y=y, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120), size=10)

# 添加图形到窗口
graphWidget.addItem(scatter)

# 显示
win.show()

上面的代码绘制了一个散点图,其中包含 10 个点。可以尝试将 xy 数组中的数据修改一下,看看图形是如何变化的。

将光标设置为散点图

将光标设置为散点图需要使用 pg.CrosshairTool 工具。下面是一个示例代码:

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui

# 创建窗口和图形区域
app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="My plot")
win.resize(1000, 600)
win.setWindowTitle('pyqtgraph example: scatter')
graphWidget = win.addPlot(title="Scatter plot")

# 准备数据
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 5, 7, 8, 1, 2, 4, 6, 9, 3]

# 绘制散点图
scatter = pg.ScatterPlotItem(x=x, y=y, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120), size=10)

# 添加图形到窗口
graphWidget.addItem(scatter)

# 设置光标为散点图
crosshair = pg.CrosshairTool()
crosshair.setPen(pg.mkPen('r', width=2))
crosshair.setPos([x[0], y[0]])
graphWidget.addItem(crosshair)

# 显示
win.show()

在第 21 行,我们创建了一个 pg.CrosshairTool() 实例,然后将其添加到了 graphWidget 上。在第 23 行,我们将光标的位置设置为第一组数据的位置。现在运行程序,可以看到光标已经变成了一个红色的十字。移动光标时,十字的位置也会随之变化。

参考资料