PyQt4, matplotlib:修改现有绘图的坐标轴标签

4
我正在使用PyQt4和matplotlib创建图表。下面这个简单的演示程序展示了我想要根据某些事件改变轴标签的内容。为了在这里进行演示,我将其设置为“指针进入”事件。程序的行为是,我只是没有看到绘图外观的任何改变。
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个回答

2

你已经接近成功了,只需要在调用 set_xlabel() 等函数后,指示 matplotlib 重新绘制图形即可。

请按以下方式修改你的程序:

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

当你把鼠标移到窗口中时,你将看到标签每次都会变化!


通常情况下,在什么条件下需要调用draw()函数来更新绘图的外观?谢谢。 - composerMike
1
如果有人遇到类似的问题,我的轴标签也不会显示出来,即使我已经调用了set_xlabel。事实证明这是一个顺序问题,必须在绘制数据后调用 set_xlabel - Rodrigo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接