Reputation: 1096
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_()
Upvotes: 4
Views: 4730
Reputation: 11849
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!
Upvotes: 2