【问题标题】:pyQt Matplotlib widget live data updatespyQt Matplotlib 小部件实时数据更新
【发布时间】:2014-05-26 20:34:55
【问题描述】:

使用 pyQt 4.8.5 在 Python 2.7 中编写:

如何在 pyQt 中实时更新 Matplotlib 小部件? 目前我正在采样数据(现在是random.gauss),附加它并绘制 - 你可以看到我每次都在清除数字并为每次调用重新绘制:

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 可以工作,尽管我认为这是实现这一目标的错误方法,因为它的效率非常低,我相信我应该在绘图时使用“动画调用”(?),虽然我不知道如何。

【问题讨论】:

  • 所以只添加新数据,旧数据保持不变?
  • 嗨,呆伯特,我应该说 - 是的,在某种程度上,这是您问题的答案。我想保留(比如说)前 500 个数据点,当新数据进来时,我会删除最旧的数据。

标签: python pyqt live


【解决方案1】:

一个想法是在第一个绘图完成后只更新图形对象。 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()

【讨论】:

  • 使用此方法时,我遇到了AttributeError: 'list' object has no attribute 'set_xdata'。这是参考self.line.set_xdata(np.arrange(len(self.ValueTotal)))。澄清一下,ValueTotal 应该被声明为一个列表,对吗?
  • self.line = self.ui.graph.axes.plot(self.ValueTotal,'r-') 应该阅读 `self.line = self.ui.graph.axes.plot(self.ValueTotal,'r-')[0]` 来解决这个问题。使用matplotlib.lines.Line2D 自己创建线实例然后使用self.ui.graph.add_line(...) 将其添加到图表中可能更有益。出于兴趣使用self.ui.graph.draw()fastest 方式更新情节?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多