📅  最后修改于: 2023-12-03 15:33:55.269000             🧑  作者: Mango
PyQtGraph是一个Python工具包,用于科学/工程应用程序的Python GUI库。它提供了高效的交互式绘图界面,包括曲线图、散点图、二维图像、直方图、等值线图和多维数据可视化等。其中,条形图也是PyQtGraph支持的一种图形,这篇文章介绍如何获取条形图的光标。
在PyQtGraph中,我们可以通过将BarGraphItem的参数设置为可选,然后使用鼠标跟踪事件和itemAt方法来获得光标位置。以下是获取光标位置的步骤:
import sys
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
app = QtGui.QApplication(sys.argv)
win = QtGui.QMainWindow()
win.setWindowTitle('PyQtGraph - 获取条形图的光标')
win.resize(800, 600)
view = pg.GraphicsLayoutWidget()
win.setCentralWidget(view)
# 创建数据
data = np.random.normal(size=10)
ticks = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
# 添加图形项
bar = pg.BarGraphItem(x=np.arange(10), height=data, width=0.5, brush=(0, 0, 255, 150),
hoverBrush=(255, 0, 0), pen='w')
view.addItem(bar)
# 设置刻度
axis = pg.AxisItem(orientation='bottom')
axis.setTicks([zip(np.arange(10), ticks)])
view.addItem(axis)
label = pg.TextItem(anchor=(0.5, 1.5))
view.addItem(label)
bar.setAcceptHoverEvents(True)
def mouseMoved(evt):
pos = evt[0] # 事件参数为QPoint对象,只需获取其坐标即可
if bar.sceneBoundingRect().contains(pos):
mousePoint = view.scene().views()[0].mapSceneToView(pos)
index = int(mousePoint.x())
label.setHtml(f"<div style='text-align: center'><span style='font-size: 18pt;'>"
f"{ticks[index]}: {data[index]:.2f}</span></div>")
label.setPos(mousePoint.x(), bar.boundingRect().bottom() + label.boundingRect().height())
else:
label.setHtml('')
bar.hoverEvent = mouseMoved
win.show()
sys.exit(app.exec_())
完整代码示例:
import sys
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
app = QtGui.QApplication(sys.argv)
win = QtGui.QMainWindow()
win.setWindowTitle('PyQtGraph - 获取条形图的光标')
win.resize(800, 600)
view = pg.GraphicsLayoutWidget()
win.setCentralWidget(view)
# 创建数据
data = np.random.normal(size=10)
ticks = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
# 添加图形项
bar = pg.BarGraphItem(x=np.arange(10), height=data, width=0.5, brush=(0, 0, 255, 150),
hoverBrush=(255, 0, 0), pen='w')
view.addItem(bar)
# 设置刻度
axis = pg.AxisItem(orientation='bottom')
axis.setTicks([zip(np.arange(10), ticks)])
view.addItem(axis)
# 创建一个文本项以显示当前光标位置
label = pg.TextItem(anchor=(0.5, 1.5))
view.addItem(label)
# 设置条形图项为可选
bar.setAcceptHoverEvents(True)
# 使用鼠标跟踪事件和itemAt方法来获得光标位置
def mouseMoved(evt):
pos = evt[0] # 事件参数为QPoint对象,只需获取其坐标即可
if bar.sceneBoundingRect().contains(pos):
mousePoint = view.scene().views()[0].mapSceneToView(pos)
index = int(mousePoint.x())
label.setHtml(f"<div style='text-align: center'><span style='font-size: 18pt;'>"
f"{ticks[index]}: {data[index]:.2f}</span></div>")
label.setPos(mousePoint.x(), bar.boundingRect().bottom() + label.boundingRect().height())
else:
label.setHtml('')
bar.hoverEvent = mouseMoved
win.show()
sys.exit(app.exec_())
运行上述代码,将弹出一个窗口,其中包含10个随机正态分布值的条形图:
当将鼠标悬停在任何一个柱子上时,将在柱子下方显示文本,用于指示该柱子的值:
通过上述步骤,我们可以轻松地通过PyQtGraph获取条形图的光标。使用这种方法,我们可以实现更高级的数据可视化应用程序,以便更好地分析和理解数据。