import sys import pyqtgraph as pg from PyQt5.QtWidgets import QApplication, QMainWindow import numpy as np class ScatterPlot(QMainWindow): def __init__(self): super().__init__() # 设置主窗口的标题 self.setWindowTitle('Scatter Plot') # 创建一个 PyqtGraph PlotWidget 对象 self.plot_widget = pg.PlotWidget() self.setCentralWidget(self.plot_widget) # 创建一个 PyqtGraph ScatterPlotItem 对象,并将其添加到 PlotWidget 中 self.scatter_plot = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120)) self.plot_widget.addItem(self.scatter_plot) # 设置数据 x = np.random.normal(size=100) y = np.random.normal(size=100) self.scatter_plot.setData(x=x, y=y) # 连接 ScatterPlotItem 的信号 clicked,使其在被单击时调用自定义的方法 self.scatter_plot.sigClicked.connect(self.on_scatter_plot_clicked) # 设置 ViewBox 的大小 self.plot_widget.getViewBox().setGeometry(pg.QtCore.QRectF(0, 0, 6, 6)) # 创建一个字典来存储每个点的高亮状态 self.highlighted_points = {i: False for i in range(len(x))} def on_scatter_plot_clicked(self, scatter_plot, points): """ 实现 ScatterPlotItem 被单击时的操作。 """ for point in points: index = point.index() # 如果该点未被高亮,则将其高亮,并将其状态设置为 True if not self.highlighted_points[index]: point.setPen(pg.mkPen('r', width=2)) point.setBrush(pg.mkBrush('r')) self.highlighted_points[index] = True # 如果该点已经被高亮,则取消高亮,并将其状态设置为 False else: point.setPen(pg.mkPen(None)) point.setBrush(pg.mkBrush(255, 255, 255, 120)) self.highlighted_points[index] = False # 将被点击的点作为屏幕中心聚焦 center = point.pos() self.plot_widget.getViewBox().setAutoPan(False) self.plot_widget.getViewBox().setRange(xRange=[center.x() - 0.5, center.x() + 0.5], yRange=[center.y() - 0.5, center.y() + 0.5], padding=0) # 刷新 PlotWidget self.plot_widget.update() if __name__ == '__main__': # 创建应用程序对象 app = QApplication(sys.argv) # 创建 ScatterPlot 对象并显示 scatter_plot = ScatterPlot() scatter_plot.show() # 运行应用程序并等待退出 sys.exit(app.exec_())