我只是想在我的程序上画一个图表。我需要使用axes.clear()
多次绘制新图表。
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MplCanvas(FigureCanvas):
def __init__(self):
self.fig = Figure()
self.axes = self.fig.add_subplot(111)
# do something...
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
# do something...
def refresh(self):
# FIXME: This method is very, very slow!!!
self.axes.clear()
# do something...
但是它很慢,它会挂起我的程序大约0.3秒。这正常吗?
我知道这是一个相当老的问题,但对于所有正在看这个(像我一样),仍然在寻找解决方案的人:
class MplCanvas(FigureCanvas):
def __init__(self):
#...
# get a reference to the line you want to plot
self.line = self.axes.plot(xdata, ydata)
def resfresh(self, xdata, ydata):
# set the new data on one or more lines
self.line.set_data(xdata, ydata)
# redraw the axis (and re-limit them)
axes.relim()
axes.autoscale_view()
# redraw the figure
self.fig.canvas.draw()
我在一个图中使用多个子图和多个轴,这加快了我已经相当多的过程。我不能进一步剥离我的代码,因为我的图表正在调整轴的大小,标题也在改变。
如果你知道你的只是想要重绘数据,使轴,标题和范围保持不变,你可以把它去掉:
def refresh(self, xdata, ydata):
# "delete" the background contents, this is only repainting an empty
# background which will look a little bit differently but I'm
# fine with it
self.axes.draw_artist(self.axes.patch)
# set the new data, could be multiple lines too
self.line.set_data(xdata, ydata)
self.axes.draw_artist(self.line)
# update figure
self.fig.canvas.update()
self.fig.canvas.flush_events()
我从这里得到了很多信息。如果你仍然想提高速度,可能有机会使用比特化,但在之前发布的链接中有写:
事实证明,
fig.canvas.blit(ax.bbox)
是一个坏主意,因为它疯狂地泄漏内存。你应该使用的是fig.canvas.update()
,它同样快,但不会泄漏内存。
我也检查了matplotlib.animation
模块,但我有一些按钮触发重画(就像问的问题),我无法找出如何在我的具体情况下使用动画。