PyQt4, matplotlib, changing the axis labels of an existing parcel

I create graphs in PyQt4 and matplotlib. The following simplified demo shows that I want to change the label on the axes in response to some kind of event. To demonstrate here, I made the event "pointer enter". The behavior of the program is that I just do not get any changes in the appearance of the plot.

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import random


class Window(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMinimumSize(400,400)
        # set up a plot but don't label the axes
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.axes = self.figure.add_subplot(111)
        h = QHBoxLayout(self)
        h.addWidget(self.canvas)

    def enterEvent(self, evt):
        # defer labeling the axes until an 'enterEvent'. then set
        # the x label
        r = int(10 * random.random())
        self.axes.set_xlabel(str(r))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    app.exec_()
+4
source share
1 answer

You are almost there. You just need to tell matplotlib to redraw the plot as soon as you finish calling functions like set_xlabel().

Change your program as follows:

def enterEvent(self, evt):
    # defer labeling the axes until an 'enterEvent'. then set
    # the x label
    r = int(10 * random.random())
    self.axes.set_xlabel(str(r))
    self.canvas.draw()

Now you will see a change in label every time you move the mouse out of the window!

+2

All Articles