如何使用Matplotblib和PyQt5将数据光标添加到条形图中?

时间:2018-07-21 20:12:19

标签: python matplotlib pyqt5

我尝试通过使用以下代码将datacursor功能添加到我的条形图中:

datacursor(hover=True, formatter=self.formatter)

没有错误发生,但是当我将鼠标指针悬停在条形上时,工具提示不显示。

我尝试将以下代码(这很完美)放入QWidget中:

import numpy as np
import matplotlib.pyplot as plt
from mpldatacursor import datacursor

label = ['a', 'b', 'c', 'd']
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]

fig, ax = plt.subplots()
ax.bar(x, y, align='center', color='lightblue')
ax.margins(0.05)
ax.set_ylim(bottom=0)

def formatter(**kwargs):
    dist = abs(np.array(x) - kwargs['x'])
    i = dist.argmin()
    return '\n'.join(label[i])

datacursor(hover=True, formatter=formatter)
plt.show()

这是我当前的代码。

后端:

from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget
from front_end import Ui_MainWindow
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from mpldatacursor import datacursor

class Ui_MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(Ui_MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.graph = MyCanvas()      
        self.gridLayout.addWidget(self.graph, 0, 0, 1, 1)
        self.populate()

    def populate(self):
        self.graph.figure.clf()
        self.axes= self.graph.figure.add_subplot(111)       
        label = ['a', 'b', 'c', 'd']
        x = [1, 2, 3, 4]
        y = [10, 20, 30, 40]
        datacursor(hover=True, formatter=self.formatter)
        self.axes.bar(x, y, align='center', bottom=0, color='b')

    def formatter(**kwargs):
        x = [1, 2, 3, 4]
        dist = abs(np.array(x) - kwargs['x'])
        i = dist.argmin()
        return '\n'.join(label[i])

class MyCanvas(FigureCanvas):
    def __init__(self, *args, **kwargs):
        self.figure = plt.figure()
        FigureCanvas.__init__(self, self.figure)
        self.figure.patch.set_facecolor("None")
        self.figure.subplots_adjust(left=0.08, bottom=0.10, right=0.99, top=0.97)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    prog = Ui_MainWindow()
    prog.show()
    sys.exit(app.exec_())

front_end:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(625, 460)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setObjectName("widget")
        self.gridLayout.addWidget(self.widget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 625, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

有几个问题。

    需要定义x方法内部使用的
  • labelformatter。一个好的解决方案是使它们成为类变量。
  • formatter方法应该是该类的方法。因此,最好使用self参数将其定义为一个。
  • 使用与导入的类相同的名称来命名类可能会引起混淆,最好以不同的方式命名。
  • datacursor需要知道要处理哪些对象,因此需要先定义条形图,然后再以这些条为参数调用datacursor函数。
  • 无需在格式化程序返回时加入任何内容,只需返回标签即可显示。

然后应该看起来像

class MyWindow(QMainWindow, Ui_MainWindow):

    # ....

    def populate(self):
        self.graph.figure.clf()
        self.axes= self.graph.figure.add_subplot(111)       
        self.label = ['a', 'b', 'c', 'd']
        self.x = [1, 2, 3, 4]
        self.y = [10, 20, 30, 40]
        bars = self.axes.bar(self.x, self.y, align='center', bottom=0, color='b')
        datacursor(bars, hover=True, formatter=self.formatter)

    def formatter(self, **kwargs):
        dist = abs(np.array(self.x) - kwargs['x'])
        i = dist.argmin()
        return self.label[i]