pyQt Matplotlib 小部件实时数据更新

2 投票
1 回答
11089 浏览
提问于 2025-04-18 07:38

我在使用 Python 2.7 和 pyQt 4.8.5 编写程序:

我想知道如何在 pyQt 中实时更新 Matplotlib 的小部件?目前我在采样数据(现在用的是随机高斯分布),然后把这些数据添加到图表中并绘制出来。你可以看到,我每次都在清空图形,然后重新绘制,这样做:

def getData(self):
    self.data = random.gauss(10,0.1)
    self.ValueTotal.append(self.data)
    self.updateData()

def updateData(self):
    self.ui.graph.axes.clear()
    self.ui.graph.axes.hold(True)
    self.ui.graph.axes.plot(self.ValueTotal,'r-')
    self.ui.graph.axes.grid()
    self.ui.graph.draw()

我的图形用户界面(GUI)虽然能正常工作,但我觉得这样做不是个好办法,因为效率太低了。我认为在绘图时应该使用“动画调用”(?),但我不知道该怎么做。

在这里输入图片描述

1 个回答

4

一个想法是,在第一次绘图完成后,只更新图形对象。axes.plot 会返回一个 Line2D 对象,你可以修改它的 x 和 y 数据:

http://matplotlib.org/api/artist_api.html#matplotlib.lines.Line2D.set_xdata

所以,一旦你绘制了这条线,就不要删除它再绘制一条新的,而是修改现有的:

def updateData(self):
    if not hasattr(self, 'line'):
        # this should only be executed on the first call to updateData
        self.ui.graph.axes.clear()
        self.ui.graph.axes.hold(True)
        self.line = self.ui.graph.axes.plot(self.ValueTotal,'r-')
        self.ui.graph.axes.grid()
    else:
        # now we only modify the plotted line
        self.line.set_xdata(np.arange(len(self.ValueTotal))
        self.line.set_ydata(self.ValueTotal)
    self.ui.graph.draw()

撰写回答