在重绘2D图时,matplotlib tkinter非常慢并且冻结

时间:2013-09-06 20:47:37

标签: python matplotlib tk

我正在尝试构建一个简单的时间序列查看器,它将具有跳到下一个时间序列的下一个按钮和一个将在整个时间序列数据集中迭代的播放按钮。即使我使用set_ydata,代码也非常慢(每秒1帧)。这和python一样好吗?当我按下播放按钮时,程序会在5-6张幻灯片后冻结。

以下是代码:

from tkinter import Tk, Button
import numpy
import matplotlib.pyplot as pyplot
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import scipy
from scipy import io

class Viewer:
    _rawData = None
    _featureMatrix = None
    _root = None
    _t = None
    _index = 0
    _T = None
    _N = None
    _plot = None
    _nextButton = None
    _figure = None
    _axes = None
    _canvas = None
    _toolbar = None
    def __init__(self, rawData, featureMatrix = []):
        # keep local copy of data
        self._rawData = rawData
        self._featureMatrix = featureMatrix
        self._T = rawData.shape[1]
        self._N = rawData.shape[0]
        self._t = numpy.arange(self._T)
        # GUI SETUP
        self._root = Tk()
        self._nextButton = Button(self._root, text="next", command = self.next)
        self._nextButton.grid(row=0, column=0)
        self._playButton = Button(self._root, text="play", command = self.play)
        self._playButton.grid(row=1, column=0)
        # init figure
        self._figure = pyplot.figure()
        self._axes = self._figure.add_subplot(111)
        self._canvas = FigureCanvasTkAgg(self._figure, master=self._root)
        self._toolbar = NavigationToolbar2TkAgg(self._canvas, self._root)
        self._canvas.get_tk_widget().grid(row=0,column=1)
        self._toolbar.grid(row=1,column=1)
        # draw first time series
        self.draw_ts()
        self._root.mainloop()
    def next(self):
        self._index = self._index + 1 % self._N
        self.draw_ts()
    def play(self):
        for i in range(self._N): self.next()
    def draw_ts(self):
        pyplot.clf() # clear figure
        #if self._plot is None:
        self._plot, = pyplot.plot(self._t, self._rawData[self._index, :]) # the annoying comma is to output an object and not a list of objects
        #else:
        #    self._plot.set_ydata(self._rawData[self._index, :])
        pyplot.title("time series index # %d / %d" % (self._index, self._N))
        #self._axes.relim()
        #self._axes.autoscale_view(True,True,True)
        self._canvas.draw()

if __name__ == "__main__":
    x = numpy.random.random([1000, 100])
    iv = Viewer(x)

1 个答案:

答案 0 :(得分:0)

哎呀,我认为是pyplot.clf()导致了很长的延迟。现在它工作得更快(仍然有点慢~7赫兹)。如果我打开游戏,它会在几张幻灯片后再次冻结。我认为这是因为它试图在完成上一个绘图之前绘制或类似的东西。