使用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工作虽然我认为这是实现这个效率非常低的错误方法,我相信我应该在绘图时使用'animate call'(?),尽管我不知道如何。
答案 0 :(得分:3)
一个想法是在第一个绘图完成后仅更新图形对象。
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()