简体   繁体   中英

PyQt4, matplotlib, modifying the axis labels of an existing plot

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM