我一直在使用 matplotlib 动画函数来显示一些实时数据。运行几分钟后,我注意到 python 使用的内存不断攀升。我决定返回一些动画示例,看看它们在我的计算机上是否存在相同的问题。
当我使用 animate_decay.py示例并将重复从 False 更改为 True,我可以模拟我的实时数据程序展示的相同问题。这是有一个更改的代码。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen(t=0):
cnt = 0
while cnt < 1000:
cnt += 1
t += 0.1
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
def init():
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 10)
del xdata[:]
del ydata[:]
line.set_data(xdata, ydata)
return line,
fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.grid()
xdata, ydata = [], []
def run(data):
# update the data
t, y = data
xdata.append(t)
ydata.append(y)
xmin, xmax = ax.get_xlim()
if t >= xmax:
ax.set_xlim(xmin, 2*xmax)
ax.figure.canvas.draw()
line.set_data(xdata, ydata)
return line,
ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
repeat=True, init_func=init, save_count=0)
plt.show()
我正在使用 Mac (OS X 10.10) 并通过 Activity Monitor 观察 python 使用的内存。随着动画一遍又一遍地重复,python 正在抢占越来越多的内存。几分钟后,python 使用了超过 300Mb。
此问题类似于以下问题:Memory usage for matplotlib animation但没有得到答复。
我曾尝试在运行函数中插入垃圾收集,但这没有帮助。我也尝试过使用 python 2.7 和 python 3.5 的 matplotlib,结果相同。还有什么建议吗?这种行为是预期的吗?
请您参考如下方法:
所以问题出在 Mac 上 matplotlib 使用的默认后端。默认后端可以通过以下方式找到:
import matplotlib
matplotlib.get_backend()
在我的迷你 Mac (OS 10.10) 上它是“MacOSX”
切换到 Qt4Agg 或 TkAgg 都可以正常工作。在前面代码的顶部插入这两行。
import matplotlib
matplotlib.use('TkAgg')
