使用Matplolib Figure和mplcursors在点上的数据标签

时间:2018-09-17 13:42:01

标签: python-3.x matplotlib hover figure

当使用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类时无法弄清楚。

0 个答案:

没有答案