pyQt Matplotlib小部件实时数据更新 [英] pyQt Matplotlib widget live data updates
问题描述
使用pyQt 4.8.5在Python 2.7中编写:
Writing in Python 2.7 using pyQt 4.8.5:
如何在pyQt中实时更新Matplotlib小部件? 目前,我正在采样数据(目前为random.gauss),并将其附加并绘制-您可以看到我每次都在清除数据并为每个调用重新绘图:
How may I update a Matplotlib widget in real time within pyQt? Currently I'm sampling data (random.gauss for now), appending this and plotting - you can see that I'm clearing the figure each time and re-plotting for each call:
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工作正常,虽然我认为这是实现效率低下的错误方法,但我认为我应该在绘图时使用动画调用"(?),尽管我不知道该怎么做.
My GUI works though I think this is the wrong way to achieve this as its highly inefficient, I believe I should use the 'animate call'(?) whilst plotting, though I don't know how.
推荐答案
一个想法是在完成第一个绘图后仅更新图形对象.
axes.plot
应该返回一个Line2D
对象,您可以修改其x和y数据:
One idea would be to update only the graphics object after the first plot was done.
axes.plot
should return a Line2D
object whose x and y-data you can modify:
http://matplotlib.org/api/artist_api.html# matplotlib.lines.Line2D.set_xdata
因此,一旦绘制了线条,就不要删除和绘制新的线条,而要修改现有的线条:
So, once you have the line plotted, don't delete and plot a new one, but modify the existing:
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()
这篇关于pyQt Matplotlib小部件实时数据更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!