4

I'm creating plots in PyQt4 and matplotlib. The following oversimplified demo program shows that I want to change the label on an axes in response to some event. For demonstrating here I'm made that a "pointer enter" event. The behavior of the program is that I simply don't get any change 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_()

1 Answer 1

2

You are almost there. You just need to instruct matplotlib to redraw the plot once you have finished calling functions like set_xlabel().

Modify 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()

You will now see the label change each time you move the mouse into the window!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. In general under what conditions does draw() need to be called to update the appearance of the plot?
If anyone stumbles upon this, I had a similar problem: my axes labels wouldn't show up even though I was calling set_xlabel. Turned out it was an ordering problem, set_xlabel must be called after the data has been drawn.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.