0

使用 mplcursors 或任何其他工具或方法,在使用 Figure 类创建的不断更新的绘图中悬停在点(只是点,而不是连接它们的线)上时,是否有任何方法可以显示数据标签?到目前为止,我看到的所有示例都使用 plt.subplot 作为创建情节的一种方式,我不想仅仅为了这个小东西而改变我的整个代码。

这是我的代码:

from PyQt5 import QtCore, QtWidgets
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import random
import sys
import mplcursors

x = []
y = []


class Ui_main_window(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui_main_window, self).__init__()
        self.setObjectName("main_window")
        self.centralwidget = QtWidgets.QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.chart_canvas = MyCanvas(self.centralwidget, width=6, height=3, dpi=100)
        self.gridLayout.addWidget(self.chart_canvas, 3, 0, 2, 6)
        self.setCentralWidget(self.centralwidget)
        self.retranslateUi(self)
        QtCore.QMetaObject.connectSlotsByName(self)
        self.show()

    def retranslateUi(self, main_window):
        _translate = QtCore.QCoreApplication.translate
        main_window.setWindowTitle(_translate("main_window", "Main Window"))


class MyCanvas(FigureCanvas):
    def __init__(self, parent=None, width=6, height=3, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = self.fig.add_subplot(111, frame_on=True)
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        mplcursors.cursor(hover=True)

        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.update_figure)
        timer.start(3000)
        self.update_figure()

    def update_figure(self):
        print("update_figure")
        (processed_time_values, processed_numeric_values) = self.value_processing()
        self.axes.cla()
        self.axes.scatter(processed_time_values, processed_numeric_values)
        self.draw()

    def value_processing(self):
        global x, y
        x.append(random.randint(0, 20))
        y.append(random.randint(0, 20))
        return x, y


app = QtWidgets.QApplication(sys.argv)
GUI_main_window = QtWidgets.QMainWindow()
main_window = Ui_main_window()
app.exec_()

此处的示例无法解决问题,窗口工作正常,但没有出现任何标签。

我也听说过注释,但是在使用 Figure 类时又无法弄清楚。

4

0 回答 0